package com.zoweunion.mechanic.service.shangji.impl;

import cn.jpush.api.push.PushResult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.obs.services.model.ObsObject;
import com.zoweunion.mechanic.dao.app.AppDao;
import com.zoweunion.mechanic.dao.app.PersonalCenterMapper;
import com.zoweunion.mechanic.dao.base.MessageRecordDao;
import com.zoweunion.mechanic.dao.shangji.ShangJiDao;
import com.zoweunion.mechanic.dao.shangji.ShangJiMapper;
import com.zoweunion.mechanic.entity.ObsUtils;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.model.app.ReportViolations;
import com.zoweunion.mechanic.plugins.jpush.JiguangPush;
import com.zoweunion.mechanic.plugins.redis.RedisUtil;
import com.zoweunion.mechanic.service.app.PersonalCenterService;
import com.zoweunion.mechanic.service.app.PushMessageRecordService;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.service.base.UserService;
import com.zoweunion.mechanic.service.shangji.ShangJiService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.constants.PushConstants;
import com.zoweunion.mechanic.util.gaode.AddressGEOUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class ShangJiServiceImpl extends BaseService implements ShangJiService {

    private final Logger logger = LoggerFactory.getLogger(ShangJiServiceImpl.class);

    public static final long EXPIRE_TIME = 3600;

    @Autowired
    private ShangJiDao shangJiDao;
    @Autowired
    private ShangJiMapper shangJiMapper;
    @Autowired
    private PersonalCenterService personalCenterService;
    @Autowired
    private PersonalCenterMapper personalCenterMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private JiGuangPushUtil jiGuangPushUtil;
    @Autowired
    private AddressGEOUtil addressGEOUtil;

    @Autowired
    private PushMessageRecordService pushMessageRecordService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private JiguangPush jiguangPush;

    @Autowired
    private AppDao appDao;

    @Autowired
    private MessageRecordDao messageRecordDao;

    @Autowired
    private RedisUtil redisUtil;
    @Resource(name = "cachedThreadPool")
    private ExecutorService cachedThreadPool;

    // 图片的上传路径

    @Value("context.image_upload_path")
    private String path;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertReportViolations(ReportViolations reportViolations) {
        reportViolations.setId(UuidUtil.get32UUID());
        return shangJiMapper.insertReportViolations(reportViolations) > 0;
    }

    /**
     * 获取推荐列表
     *
     * @param reqMap
     * @return
     */
    @Override
    public List<Map<String, Object>> listRecommend(Map<String, Object> reqMap) throws Exception {
        String recommendType = reqMap.get("recommendType").toString();
        this.appPage(reqMap);
        reqMap.put("isRecommend", true);
        // 1-维修 2-出售 3-出租 4-招标 5-新闻 6-招聘
        if ("1".equals(recommendType)) {
            this.setLonLat(reqMap);
            return shangJiDao.getShopList(reqMap);
        } else if ("2".equals(recommendType)) {
            reqMap.put("type", "出售");
            List<Map<String, Object>> mapList = shangJiDao.getPublicCarInfo(reqMap);
            mapList.forEach(map -> map.put("price", this.priceHandle(map)));
            return mapList;
        } else if ("3".equals(recommendType)) {
            reqMap.put("type", "出租");
            List<Map<String, Object>> mapList = shangJiDao.getPublicCarInfo(reqMap);
            mapList.forEach(map -> map.put("price", this.priceHandle(map)));
            return mapList;
        } else if ("4".equals(recommendType)) {
            reqMap.put("dataType", "1");
            return shangJiDao.getzhongbiaoList(reqMap);
        } else if ("5".equals(recommendType)) {
            return shangJiDao.getNewsList(reqMap);
        } else if ("6".equals(recommendType)) {
            return shangJiDao.getRecruitInfoList(reqMap);
        } else {
            this.setLonLat(reqMap);
            return shangJiDao.getShopList(reqMap);
        }
    }

    private void setLonLat(Map<String, Object> reqMap) {
        if (reqMap.get("location") != null && StringUtils.isNotBlank(reqMap.get("location").toString())) {
            //取前端传过来的用户的经纬度
            String location = reqMap.get("location").toString();
            String lon = location.substring(0, location.indexOf(","));
            String lat = location.substring(location.indexOf(",") + 1);
            reqMap.put("lon", lon);
            reqMap.put("lat", lat);
        }
    }

    @Override
    public List<Map<String, Object>> listBrand(Map<String, Object> reqMap) {
        List<Map<String, Object>> brandList = shangJiMapper.listBrand(reqMap);
        return this.categoryBrand(brandList);
    }

    @Override
    public Map<String, Object> listBrandClassify(Map<String, Object> reqMap) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> brandList = shangJiMapper.listBrand(reqMap);
        resultMap.put("brands", this.categoryBrand(brandList));
        //获取热门品牌 返回速度很慢，暂时去掉
        //resultMap.put("hotBrands", shangJiMapper.getHotMechanicsBrand());

        return resultMap;
    }

    /**
     * 分组品牌
     *
     * @param brandList
     * @return
     */
    private List<Map<String, Object>> categoryBrand(List<Map<String, Object>> brandList) {
        List<Map<String, Object>> initials = new ArrayList<>();
        //根据首字母分类
        String az = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
        if (brandList.size() > 0) {
            for (int i = 0; i < az.length(); i++) {
                char c = az.charAt(i);
                Map<String, Object> initialsMap = new HashMap<>();
                List<Map<String, Object>> initialsList = new ArrayList<>();
                for (Map<String, Object> brandMap : brandList) {
                    if (brandMap.get("initials").equals(String.valueOf(c))) {
                        initialsList.add(brandMap);
                    }
                }
                if (initialsList.size() > 0) {
                    initialsMap.put("name", c);
                    initialsMap.put("list", initialsList);
                    initials.add(initialsMap);
                }
            }
        }
        return initials;
    }

    /**
     * 为租售表设置经纬度
     */
    @Override
    public void setLatitudeAndLongitudeForBuyInfo() throws MyException {
        // 获取没有经纬度的列表数据
        List<Map<String, String>> buyInfoList = shangJiMapper.listNoLongitude();
        for (Map<String, String> buyInfo : buyInfoList) {
            String province = buyInfo.get("province");
            String city = buyInfo.get("city");
            Map<String, String> geoMap = addressGEOUtil.geoNew(province + city, city);
            if (geoMap == null) {
                continue;
            }
            geoMap.put("id", buyInfo.get("id"));
            shangJiMapper.saveLatitudeAndLongitudeForBuyInfo(geoMap);
        }
    }

    /**
     * 为维修商铺表设置经纬度
     */
    @Override
    public void setLatitudeAndLongitudeForShopInfo() throws MyException {
        // 获取没有经纬度的列表数据
        List<Map<String, String>> buyInfoList = shangJiMapper.listNoLongitudeWithShopInfo();
        for (Map<String, String> buyInfo : buyInfoList) {
            String province = buyInfo.get("province");
            String city = buyInfo.get("city");
            Map<String, String> geoMap = addressGEOUtil.geoNew(province + city, city);
            if (geoMap == null) {
                continue;
            }
            geoMap.put("id", buyInfo.get("id"));
            shangJiMapper.saveLatitudeAndLongitudeForShopInfo(geoMap);
        }
    }

    /**
     * 设置维修店铺评价
     */
    @Override
    public void setEvaluationsForShopInfo() throws MyException {
        // 获取没有评价的的列表数据
        List<Map<String, String>> mapList = shangJiMapper.listNoEvaluationsWithShopInfo();
        for (Map<String, String> map : mapList) {
            map.put("evaluations", this.returnEvaluations());
            shangJiMapper.saveEvaluationsForShopInfo(map);
        }
    }

    private String returnEvaluations() {
        String evaluation1 = this.createEvaluation();
        String evaluation2 = this.createEvaluation();
        return this.removeRepeatEvaluation(evaluation1, evaluation2);
    }

    private String removeRepeatEvaluation(String evaluation1, String evaluation2) {
        if (evaluation1.equals(evaluation2)) {
            return this.removeRepeatEvaluation(evaluation1, this.createEvaluation());
        }
        return evaluation1 + "," + evaluation2;
    }

    private String createEvaluation() {
        String[] evaluations = new String[]{"技术好", "价格合理", "时间快"};
        int randomNum = (int) (Math.random() * evaluations.length);
        return evaluations[randomNum];
    }

    @Override
    public void setWorkTypeRandom() throws MyException {
        List<Map<String, String>> mapList = shangJiMapper.listNoWorkTypeWithJoberInfo();
        for (Map<String, String> map : mapList) {
            map.put("type_name", this.createWorkTypeRandom());
            shangJiMapper.saveWorkTypeForJoberInfo(map);
        }
        mapList = shangJiMapper.listNoWorkTypeWithRecruitInfo();
        for (Map<String, String> map : mapList) {
            map.put("type_name", this.createWorkTypeRandom());
            shangJiMapper.saveWorkTypeForRecruitInfo(map);
        }
    }

    @Override
    public void setRentalMethodForBuyInfoRandom() throws MyException {
        List<Map<String, String>> mapList = shangJiMapper.listRentalMethodForBuyInfo();
        for (Map<String, String> map : mapList) {
            map.put("rental_method", this.createRentalMethodRandom());
            shangJiMapper.saveRentalMethodForBuyInfo(map);
        }
    }

    private String createRentalMethodRandom() {
        String[] workType = new String[]{"月租", "季租", "年租", "其他"};
        int randomNum = (int) (Math.random() * workType.length);
        return workType[randomNum];
    }

    private String createWorkTypeRandom() {
        String[] workType = new String[]{"销售", "学徒", "机手", "维修工"};
        int randomNum = (int) (Math.random() * workType.length);
        return workType[randomNum];
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> publish(User user, Map<String, Object> reqMap) throws MyException {

        // 获取原始文件名
//		String originalFilename = file.getOriginalFilename();
//		if (originalFilename != null) {
//			// 生成图片的名字
//			String imageName = UploadFileUtils.getFileName(originalFilename);
//			// 生成新的文件名
//			String realPath = path + imageName;
//			// 上传图片
//			Boolean flag = UploadFileUtils.upload(file, realPath);
//			if (flag == false) {
//				throw new MyException(Constants.CODE_HANDEL_FAILED, "图片上传失败");
//			}
//			// 将图片名字封装到map中
//			reqMap.put("imageName", imageName);
//		}else {
//			reqMap.put("imageName", null);
//		}
//		reqMap.put("image_name", null);
        // 将发布的相关信息发布信息保存到数据库中
        String id = UuidUtil.get32UUID();
        reqMap.put("id", id);
        String address = reqMap.get("detail_address").toString();
        //调用高德地图 将地址转换为经纬度
        String gaodeJson = restTemplate.getForObject(
                "https://restapi.amap.com/v3/geocode/geo?key=e4dff7935045e4aadf06e230816b9fcc&address="
                        + address + "&city=" + reqMap.get("city").toString(), String.class);
        //判断是否查询失败
        if (JSONObject.parseObject(gaodeJson).getString("status").equals("0")) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "业务操作失败");
        }
        JSONArray geocodes = JSONObject.parseObject(gaodeJson).getJSONArray("geocodes");
        if (geocodes.size() == 0) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "请填写正确的地址");
        }
        JSONObject info = geocodes.getJSONObject(0);
        //取地址经纬度
        String location = info.getString("location");
        reqMap.put("longitude", location.substring(0, location.indexOf(",")));
        reqMap.put("latitude", location.substring(location.indexOf(",") + 1));

        reqMap.put("type_name", String.join(",", (List<String>) reqMap.get("type_name")));
        isCompanyApply(user.getId(), reqMap);
        int i = shangJiDao.publish(reqMap);
        if (i != 1) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "业务操作失败");
        }
        // 生成我的发布记录
        this.saveMyRelease(user.getId(), user.getUser_name(), id, Constants.PublishTypeEnum.publish_type_weixiu.getType(), reqMap.get("shop_name").toString());
        // 做任务获取积分
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id", "2");
        personalCenterService.completeTask(user, paramsMap);
        // app推送通知
        String msg = user.getUser_name() + "发布了商铺信息，请尽快审核";
        this.publishApPushpNoticeAssignPerson(msg, user.getId());
        Map<String, Object> map = new HashMap<>(16);
        map.put("id", id);
        return map;

    }

//	public int uploadPhoto(MultipartFile file) throws MyException {
//		// 获取原始文件名
//		String originalFilename = file.getOriginalFilename();
//		if (originalFilename != null) {
//			// 生成图片的名字
//			String imageName = UploadFileUtils.getFileName(originalFilename);
//			// 生成新的文件名
//			String realPath = path + imageName;
//			// 上传图片
//			Boolean flag = UploadFileUtils.upload(file, realPath);
//			if (flag == false) {
//				throw new MyException(Constants.CODE_HANDEL_FAILED, "图片上传失败");
//			}
//		}else {
//		}
//		return 0;
//	}

    @Override
    public List<Map<String, Object>> getShopList(Map<String, Object> reqMap, User currentUser, String device) throws MyException {
        //取当前页
        String currentPage = reqMap.get("currentPage").toString();
        //分页数据
        this.appPage(reqMap);
        // 如果市有值，省无值，查询省
        if ((reqMap.get("province") != null && StringUtils.isNotBlank(reqMap.get("city").toString())) && (reqMap.get("province") == null || StringUtils.isBlank(reqMap.get("province").toString()))) {
            reqMap.put("province", shangJiMapper.getProvinceByCityName(reqMap.get("city").toString()).get("cityName"));
        }
        if (reqMap.get("sort_mode").toString().equals("2")) {
            List<Map<String, Object>> list = shangJiDao.getShopList(reqMap);
            return list;
        }
        //取前端传过来的用户的经纬度
        String userLonLat = reqMap.get("lonLat").toString();
        String lon = userLonLat.substring(0, userLonLat.indexOf(","));
        String lat = userLonLat.substring(userLonLat.indexOf(",") + 1);
        reqMap.put("lon", lon);
        reqMap.put("lat", lat);
        //调用高德地图 将地址转换为经纬度province
        String gaodeJson = restTemplate.getForObject(
                "https://restapi.amap.com/v3/geocode/regeo?key=e4dff7935045e4aadf06e230816b9fcc&location="
                        + userLonLat, String.class);
        String regeocode = JSONObject.parseObject(gaodeJson).getString("regeocode");
        String addressComponent = JSONObject.parseObject(regeocode).getString("addressComponent");
        //取地址省市
        String province = JSONObject.parseObject(addressComponent).getString("province");
        String city = JSONObject.parseObject(addressComponent).getString("city");
        //判断所选城市是不是当前城市
        if (!province.equals(reqMap.get("province").toString()) || !city.equals(reqMap.get("city").toString())) {
            List<Map<String, Object>> list = shangJiDao.getSortShopList(reqMap);
            return list;
        }

        //判断redis里有没有
        boolean isRedis = redisUtil.exists(reqMap.get("u_id").toString() + "list");
        if (isRedis == true) {
            //取redis数据
            List<Map<String, Object>> sortList = (List<Map<String, Object>>) redisUtil.get(reqMap.get("u_id").toString() + "list");
            if (StringUtils.isNotBlank(reqMap.get("type_name").toString())) {
                List<Map<String, Object>> typeList = new ArrayList<>();
                for (Map<String, Object> map : sortList) {
                    if (map.get("type_name") != null && map.get("type_name").toString().contains(reqMap.get("type_name").toString())) {
                        typeList.add(map);
                    }
                }
                reqMap.remove("type_name");
                sortList = typeList;
            }
            //分页
            Map<String, Object> pageMap = getPageShopList(sortList);
            List<Map<String, Object>> mapList = (List<Map<String, Object>>) pageMap.get(currentPage);
            new Thread(() -> {
                try {
                    getSortShopList(reqMap);
                } catch (MyException e) {
                    e.printStackTrace();
                }
            }).start();
            return mapList;
        }
        //redis 没有  执行
        List<Map<String, Object>> sortList = getSortShopList(reqMap);
        Map<String, Object> pageMap = getPageShopList(sortList);
        List<Map<String, Object>> mapList = (List<Map<String, Object>>) pageMap.get(currentPage);

        logger.info("进入维修服务列表加分");
        insertUserBehavior(reqMap, Constants.BEHAVIOR_SHOP_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_LIST.getBehavior(), currentUser, device);
        return mapList;
    }

    @Override
    public int getShopListCount(Map<String, Object> reqMap) {
        //分页数据
        Map<String, Object> page = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", page.get("limit"));
        reqMap.put("currentPage", page.get("offset"));
        // 如果市有值，省无值，查询省
        if ((reqMap.get("province") != null && StringUtils.isNotBlank(reqMap.get("city").toString())) && (reqMap.get("province") == null || StringUtils.isBlank(reqMap.get("province").toString()))) {
            reqMap.put("province", shangJiMapper.getProvinceByCityName(reqMap.get("city").toString()).get("cityName"));
        }
        return shangJiDao.getShopListCount(reqMap);
    }

    @Override
    public List<Map<String, Object>> getShopListNew(Map<String, Object> reqMap, User currentUser, String device) throws MyException {
        //分页数据
        if (reqMap.get("currentPage") != null) {
            this.appPage(reqMap);
        }
        // 如果市有值，省无值，查询省
        if ((reqMap.get("province") != null && StringUtils.isNotBlank(reqMap.get("city").toString())) && (reqMap.get("province") == null || StringUtils.isBlank(reqMap.get("province").toString()))) {
            reqMap.put("province", shangJiMapper.getProvinceByCityName(reqMap.get("city").toString()).get("cityName"));
        }
        //取前端传过来的用户的经纬度
        this.setLonLat(reqMap);
		cachedThreadPool.execute(() -> {
			if (reqMap.get("type_name") != null && !"".equals(reqMap.get("type_name").toString())) {
				logger.info("维修服务有条件的筛选加分");
				insertUserBehavior(reqMap, Constants.BEHAVIOR_SHOP_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_SEARCH.getBehavior(), currentUser, device);
			} else {
				logger.info("进入维修服务列表加分");
				insertUserBehavior(reqMap, Constants.BEHAVIOR_SHOP_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_LIST.getBehavior(), currentUser, device);
			}
		});
        return shangJiDao.getShopList(reqMap);
    }

    /**
     * 查询店铺列表在进行按距离排序 存入redis
     *
     * @param reqMap
     * @return
     * @throws MyException
     */
    public List<Map<String, Object>> getSortShopList(Map<String, Object> reqMap) throws MyException {
        // 获取店铺列表
        List<Map<String, Object>> list = shangJiDao.getShopList(reqMap);
        if (list.size() == 0) {
            return list;
        }
        int listSize = list.size();
        int toIndex = 10;
        List<Map<String, Object>> sortList = new ArrayList<>();
        for (int i = 0; i < list.size(); i += 10) {
            //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
            if (i + 10 > listSize) {
                toIndex = listSize - i;
            }
            List<Map<String, Object>> newList = list.subList(i, i + toIndex);
            String lonLat = "";
            for (Map<String, Object> map : newList) {
                String lon = map.get("longitude").toString();
                String lat = map.get("latitude").toString();
                lonLat += lon + "," + lat + "|";
            }
            //取前端传过来的用户的经纬度
            String userLonLat = reqMap.get("lonLat").toString();
            //取前端传过来的距离类型
            String type = reqMap.get("type").toString();
            //调用高德地图 算距离
            String distanceJson = restTemplate.getForObject(
                    "https://restapi.amap.com/v3/distance?key=e4dff7935045e4aadf06e230816b9fcc&origins="
                            + lonLat + "&destination=" + userLonLat + "&type=" + type, String.class);
            //判断是否查询失败
            if (JSONObject.parseObject(distanceJson).getString("status").equals("0")) {
                throw new MyException(Constants.CODE_HANDEL_FAILED, "业务操作失败");
            }
            JSONArray results = JSONObject.parseObject(distanceJson).getJSONArray("results");
            for (int j = 0; j < results.size(); j++) {
                JSONObject info = results.getJSONObject(j);
                //取距离
                String distance = info.getString("distance");
                Map<String, Object> map = newList.get(j);
                map.put("distance", distance);
            }
            sortList.addAll(newList);
        }
        //将算好距离的 放进redis
        Collections.sort(sortList, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                //distance1是从你list里面拿出来的一个
                Integer distance1 = Integer.valueOf(o1.get("distance").toString());
                //distance2是从你list里面拿出来的第二个
                Integer distance2 = Integer.valueOf(o2.get("distance").toString());
                return distance1.compareTo(distance2);
            }
        });
        redisUtil.set(reqMap.get("u_id").toString() + "list", sortList, EXPIRE_TIME);
        return sortList;
    }

    /**
     * 将list分页
     *
     * @param sortList
     * @return
     */
    public Map<String, Object> getPageShopList(List<Map<String, Object>> sortList) {
        int sortListSize = sortList.size();
        int toIndex = 10;
        int keyToken = 1;
        Map<String, Object> pageMap = new HashMap<>();
        for (int i = 0; i < sortList.size(); i += 10) {
            //作用为toIndex最后没有10条数据则剩余几条newList中就装几条
            if (i + 10 > sortListSize) {
                toIndex = sortListSize - i;
            }
            List<Map<String, Object>> newList = sortList.subList(i, i + toIndex);
            pageMap.put(String.valueOf(keyToken), newList);
            keyToken++;
        }
        return pageMap;
    }

    /**
     * 获取商机店铺详情
     */
    @Override
    public Map<String, Object> getShopInfo(Map<String, Object> reqMap, User currentUser, String device) throws Exception {
        Map<String, Object> result = shangJiDao.getShopInfo(reqMap);
        if (currentUser != null && result.get("shop_name") != null && result.get("create_user") != null) {
            String context = result.get("shop_name").toString();
            String receiver = result.get("create_user").toString();
            reqMap.put("context", context);
            reqMap.put("receive_user", receiver);
            reqMap.put("send_type", 10);
            personalCenterService.pushVisitMessage(reqMap, currentUser, context);
        }
        //调用高德地图 算距离
        String location = reqMap.get("location") + "";
        String destination = result.get("longitude") + "," + result.get("latitude");
        result.put("distance", addressGEOUtil.getDistanceMap(location, destination, "1"));
        int resultUpdate = shangJiDao.updateShopBrowse(result);
		cachedThreadPool.execute(() -> {
			logger.info("进入维修服务详情加分");
			insertUserBehavior(reqMap, Constants.BEHAVIOR_SHOP_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_DETAIL.getBehavior(), currentUser, device);
		});
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateShopExamineFlag(Map<String, Object> map) throws Exception {
        map.put("update_time", new Date());
        if (map.get("ids") == null || StringUtils.isBlank(map.get("ids").toString())) {
            map.put("isPcBatchCheck", true);
        }
        shangJiDao.updateShopExamineFlag(map);
        return true;
    }

    @Override
    public List<Map<String, Object>> getzhongbiaoList(Map<String, Object> reqMap, User currentUser, String device) throws Exception {
        Semaphore semaphore = new Semaphore(20);
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));

        // 如果市有值，省无值，查询省
        if ((reqMap.get("province") != null && StringUtils.isNotBlank(reqMap.get("city").toString())) && (reqMap.get("province") == null || StringUtils.isBlank(reqMap.get("province").toString()))) {
            reqMap.put("province", shangJiMapper.getProvinceByCityName(reqMap.get("city").toString()).get("cityName"));
        }
//		if (reqMap.get("startTime") == null) {
//			// 获取前6个月
//			LocalDate date = LocalDate.now();
//			date = date.minusMonths(5).with(TemporalAdjusters.firstDayOfMonth());
//			reqMap.put("startTime", date.toString());
//		}
        // 获取中标列表
        List<Map<String, Object>> list = shangJiMapper.getZhaobiaoProject(reqMap);
        cachedThreadPool.execute(() -> {
            if (reqMap.get("startTime") != null || Integer.parseInt(reqMap.get("dataType").toString()) != 0) {
                logger.info("招中标有筛选的搜索加分");
                insertUserBehavior(reqMap, Constants.BEHAVIOR_BID_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_SEARCH.getBehavior(), currentUser, device);
            } else {
                logger.info("进入招中标列表加分");
                insertUserBehavior(reqMap, Constants.BEHAVIOR_BID_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_LIST.getBehavior(), currentUser, device);
            }
        });


        // 转换星期几
        //		for (Map<String, Object> map : list) {
//			if (map.containsKey("createTime") && map.get("createTime").toString().length() > 0) {
//				LocalDate date = LocalDate.parse(map.get("createTime").toString().substring(0, 10));
//				map.put("week", DateUtil.weekObject(date.getDayOfWeek().getValue()));
//			}
//		}

        // 执行分页逻辑
//		List<Map<String, Object>> resultList = Page.excutePage(list, reqMap);

        // 返回结果
        return list;
    }

    /**
     * 获取招中标详情
     */
    @Override
    public List<Map<String, Object>> getzhongbiaoInfo(Map<String, Object> reqMap, User currentUser, String device) throws Exception {
        List<Map<String, Object>> map = shangJiDao.getzhongbiaoInfoNew(reqMap);
		cachedThreadPool.execute(() -> {
			logger.info("获取招中标详情加分");
			insertUserBehavior(reqMap, Constants.BEHAVIOR_BID_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_DETAIL.getBehavior(), currentUser, device);
		});
        return map;

    }

    @Override
    public int publishCars(Map<String, Object> reqMap) throws Exception {
        int i = shangJiDao.publishCars(reqMap);
        if (i != 1) {

            throw new MyException(Constants.CODE_HANDEL_FAILED, "业务操作失败");

        }
        return i;

    }

    @Override
    public List<Map<String, Object>> getpublishCarsList(Map<String, Object> reqMap) throws Exception {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        // 获取店铺列表
        List<Map<String, Object>> list = shangJiDao.getpublishCarsList(reqMap);
        // 执行分页逻辑
//		List<Map<String, Object>> resultList = Page.excutePage(list, reqMap);
        // 返回结果
        return list;
    }

    @Override
    public int publishBuyerInfo(Map<String, Object> reqMap) throws Exception {
        int i = shangJiDao.publishBuyerInfo(reqMap);
        if (i != 1) {

            throw new MyException(Constants.CODE_HANDEL_FAILED, "业务操作失败");

        }
        return i;
    }

    @Override
    public List<Map<String, Object>> getpublishBuyerInfoList(Map<String, Object> reqMap) throws Exception {
        // 获取店铺列表
        List<Map<String, Object>> list = shangJiDao.getpublishBuyerInfoList(reqMap);
        // 执行分页逻辑
        List<Map<String, Object>> resultList = Page.excutePage(list, reqMap);
        // 返回结果
        return resultList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> publishJoberInfo(User user, Map<String, Object> reqMap) throws Exception {
//		reqMap.put("drive_age",Integer.valueOf(reqMap.get("drive_age").toString()));
        String id = UuidUtil.get32UUID();
        reqMap.put("id", id);
        String subject = "求职" + reqMap.get("type_name").toString();
        reqMap.put("subject", subject);
        isCompanyApply(user.getId(), reqMap);
        int i = shangJiDao.publishJoberInfo(reqMap);
        if (i != 1) {

            throw new MyException(Constants.CODE_HANDEL_FAILED, "业务操作失败");

        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("id", id);
        // 生成我的发布记录
        this.saveMyRelease(user.getId(), user.getUser_name(), id, Constants.PublishTypeEnum.publish_type_qiuzhi.getType(), reqMap.get("subject").toString());
        // 获取积分
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id", "2");
        personalCenterService.completeTask(user, paramsMap);
        // app推送
        String msg = user.getUser_name() + "发布了求职信息，请尽快审核";
        this.publishApPushpNoticeAssignPerson(msg, user.getId());
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateJoberExamineFlag(Map<String, Object> map) throws Exception {
        map.put("update_time", new Date());
        if (map.get("ids") == null || StringUtils.isBlank(map.get("ids").toString())) {
            map.put("isPcBatchCheck", true);
        }
        shangJiDao.updateJoberExamineFlag(map);
        return true;
    }

    @Override
    public Map<String, Object> getJoberInfoList(Map<String, Object> reqMap, User currentUser, String device) throws Exception {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        // 如果市有值，省无值，查询省
        if ((reqMap.get("province") != null && StringUtils.isNotBlank(reqMap.get("city").toString())) && (reqMap.get("province") == null || StringUtils.isBlank(reqMap.get("province").toString()))) {
            reqMap.put("province", shangJiMapper.getProvinceByCityName(reqMap.get("city").toString()).get("cityName"));
        }
        // 获取店铺列表
        List<Map<String, Object>> list = shangJiDao.getJoberInfoList(reqMap);
//		Integer count = shangJiDao.getJoberInfoCount(reqMap);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
//		map.put("total",count);
        // 返回结果
		cachedThreadPool.execute(() -> {
			String type = reqMap.get("type_name").toString();
			if (!"".equals(type)) {
				logger.info("个人求职列表搜索");
				insertUserBehavior(reqMap, Constants.BEHAVIOR_RECRUIT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_SEARCH.getBehavior(), currentUser, device);
			} else {
				logger.info("进入个人求职列表加分");
				insertUserBehavior(reqMap, Constants.BEHAVIOR_RECRUIT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_LIST.getBehavior(), currentUser, device);
			}
		});
        return map;
    }

    @Override
    public Map<String, Object> getJoberInfo(Map<String, Object> reqMap, User currentUser, String device) throws Exception {
        // 返回结果
        Map<String, Object> result = shangJiDao.getJoberInfo(reqMap);
        if (currentUser != null && result.get("subject") != null && result.get("create_user") != null) {
            String context = result.get("subject").toString();
            String receiver = result.get("create_user").toString();
            reqMap.put("context", context);
            reqMap.put("receive_user", receiver);
            reqMap.put("send_type", 10);
            personalCenterService.pushVisitMessage(reqMap, currentUser, context);
        }
        int resultUpdate = shangJiDao.updateJoberBrowse(result);
		cachedThreadPool.execute(() -> {
			logger.info("进入个人求职详情页面加分");
			insertUserBehavior(reqMap, Constants.BEHAVIOR_RECRUIT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_DETAIL.getBehavior(), currentUser, device);
		});
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> publishRecruitInfo(User user, Map<String, Object> reqMap) throws Exception {
        String id = UuidUtil.get32UUID();
        reqMap.put("id", id);
        List<String> treatments = (List<String>) reqMap.get("treatment");
        reqMap.put("treatment", String.join(",", treatments));
        String subject = "急需" + reqMap.get("type_name").toString();
        reqMap.put("subject", subject);
        //判断该发布人是否是企业认证过 如果是则isCompany为1 否则为0
        isCompanyApply(user.getId(), reqMap);
        int i = shangJiDao.publishRecruitInfo(reqMap);
        if (i != 1) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "业务操作失败");
        }
        // 生成我的发布记录
        this.saveMyRelease(user.getId(), user.getUser_name(), id, Constants.PublishTypeEnum.publish_type_zhaopin.getType(), reqMap.get("subject").toString());
        // 获取积分
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id", "2");
        personalCenterService.completeTask(user, paramsMap);
        Map<String, Object> map = new HashMap<>(16);
        map.put("id", id);
        String msg = user.getUser_name() + "发布了招聘信息，请尽快审核";
        this.publishApPushpNoticeAssignPerson(msg, user.getId());
        return map;
    }

    /**
     * 判断该发布的发布人是否企业认证过 如果是 则把isCompany置为1 否则为0
     *
     * @param id
     * @param reqMap
     */
    public void isCompanyApply(String id, Map<String, Object> reqMap) {
        int isCompany = shangJiMapper.getIsCompany(id);
        if (isCompany == 0) {
            reqMap.put("isCompany", '0');
        } else if (isCompany == 1) {
            reqMap.put("isCompany", '1');
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRecruitExamineFlag(Map<String, Object> map) throws Exception {
        map.put("update_time", new Date());
        if (map.get("ids") == null || StringUtils.isBlank(map.get("ids").toString())) {
            map.put("isPcBatchCheck", true);
        }
        shangJiDao.updateRecruitExamineFlag(map);
        return true;
    }

    @Override
    public Map<String, Object> getRecruitInfoList(Map<String, Object> reqMap, User currentUser, String device) throws Exception {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        // 如果市有值，省无值，查询省
        if ((reqMap.get("province") != null && StringUtils.isNotBlank(reqMap.get("city").toString())) && (reqMap.get("province") == null || StringUtils.isBlank(reqMap.get("province").toString()))) {
            reqMap.put("province", shangJiMapper.getProvinceByCityName(reqMap.get("city").toString()).get("cityName"));
        }
        // 获取店铺列表
        List<Map<String, Object>> list = shangJiDao.getRecruitInfoList(reqMap);
//		Integer count = shangJiDao.getRecruitInfoCount(reqMap);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
//		map.put("total",count);
        // 执行分页逻辑
//		List<Map<String, Object>> resultList = Page.excutePage(list, reqMap);
		cachedThreadPool.execute(() -> {
			if (!"".equals(reqMap.get("type_name").toString())) {
				logger.info("招聘列表搜索");
				insertUserBehavior(reqMap, Constants.BEHAVIOR_RECRUIT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_SEARCH.getBehavior(), currentUser, device);
			} else {
				logger.info("进入招聘列表加分");
				insertUserBehavior(reqMap, Constants.BEHAVIOR_RECRUIT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_LIST.getBehavior(), currentUser, device);
			}
		});
        return map;
    }

    @Override
    public Map<String, Object> getRecruitInfo(Map<String, Object> reqMap, User currentUser, String device) throws Exception {
        // 返回结果
        Map<String, Object> map = shangJiDao.getRecruitInfo(reqMap);
        if (currentUser != null && map.get("subject") != null && map.get("create_user") != null) {
            String context = map.get("subject").toString();
            String receiver = map.get("create_user").toString();
            reqMap.put("context", context);
            reqMap.put("receive_user", receiver);
            reqMap.put("send_type", 10);
            personalCenterService.pushVisitMessage(reqMap, currentUser, context);
        }
        int result = shangJiDao.updateRecruitBrowse(map);
		cachedThreadPool.execute(() -> {
			logger.info("进入招聘详情页面加分");
			insertUserBehavior(reqMap, Constants.BEHAVIOR_RECRUIT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_DETAIL.getBehavior(), currentUser, device);
		});
        return map;
    }

    @Override
    public List<Map<String, Object>> getCarType(Map<String, Object> reqMap) throws Exception {

        List<Map<String, Object>> infoList = shangJiMapper.getCarType(reqMap);
		/*List<Map<String, Object>> infoList = shangJiDao.getCarTypeM(reqMap);
		//select id,parent_id,type_name from vehicle_type_new where parent_id = '0'
		for (Map<String, Object> map : infoList) {

			reqMap.put("parent_id", map.get("id"));

			List<Map<String, Object>> typeList = shangJiDao.getCarTypeS(reqMap);

			if (typeList.size() > 0) {
				map.put("type", typeList);
			}
		}*/

        return infoList;
    }

    @Override
    public List<Map<String, Object>> getCarBrand(Map<String, Object> reqMap) throws Exception {

        List<Map<String, Object>> brandList = shangJiDao.getCarBrand(reqMap);

        return brandList;
    }

    @Override
    public List<Map<String, Object>> getCarModel(Map<String, Object> reqMap) throws Exception {

        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(), reqMap.get("currentPage").toString());

        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));

        if (reqMap.get("currentPage").toString().equals("0") && reqMap.get("parent_id") != null && reqMap.get("brand_id").toString().equals("")) {

            shangJiMapper.updateCarTypeClickCount(reqMap);
        }

        List<Map<String, Object>> modelList = shangJiMapper.getVehicleModel(reqMap);

        return modelList;
    }


    @Override
    public Map<String, Object> getPublicCarInfo(User user, Map<String, Object> reqMap, String device) throws Exception {
        // 如果市有值，省无值，查询省
        if ((reqMap.get("province") != null && StringUtils.isNotBlank(reqMap.get("city").toString())) && (reqMap.get("province") == null || StringUtils.isBlank(reqMap.get("province").toString()))) {
            reqMap.put("province", shangJiMapper.getProvinceByCityName(reqMap.get("city").toString()).get("cityName"));
        }

        Map<String, Object> resultMap = new HashMap<>();
        // 判断是地图显示还是列表显示
        if (reqMap.get("ids") != null && StringUtils.isNotBlank(reqMap.get("ids").toString())) {
            int pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
            int currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
            List<String> ids = (List<String>) reqMap.get("ids");
            int idSize = ids.size();
            if (idSize > 0) {
                if ((currentPage - 1) * pageSize < idSize) {
                    if (currentPage * pageSize > idSize) {
                        reqMap.put("ids", String.join(",", ids.subList((currentPage - 1) * pageSize, idSize)));
                    } else {
                        reqMap.put("ids", String.join(",", ids.subList((currentPage - 1) * pageSize, currentPage * pageSize)));
                    }
                } else {
                    resultMap.put("modelList", Collections.emptyList());
                    return resultMap;
                }
            }
        } else {
            if (reqMap.get("currentPage") != null) {
                this.appPage(reqMap);
            }
        }
        // 价格查询
        if (reqMap.get("price") != null && StringUtils.isNotBlank(reqMap.get("price").toString())) {
            String price = reqMap.get("price").toString();
            if ("0".equals(price)) {
                reqMap.put("priceS", "");
                reqMap.put("priceE", "");
            } else if ("1".equals(price)) {
                reqMap.put("priceS", "0.000000001");
                reqMap.put("priceE", "10");
            } else if ("2".equals(price)) {
                reqMap.put("priceS", "10");
                reqMap.put("priceE", "20");
            } else if ("3".equals(price)) {
                reqMap.put("priceS", "20");
                reqMap.put("priceE", "30");
            } else if ("4".equals(price)) {
                reqMap.put("priceS", "30");
                reqMap.put("priceE", "40");
            } else if ("5".equals(price)) {
                reqMap.put("priceS", "40");
                reqMap.put("priceE", "50");
            } else if ("6".equals(price)) {
                reqMap.put("priceS", "50");
                reqMap.put("priceE", "");
            }
        }
        reqMap.put("isGuest", this.isGuest(user));
        if (!this.isGuest(user)) {
            reqMap.put("isCarMasterOrDriver", Constants.ROLE_SJ.equals(user.getR_id()) || Constants.ROLE_CZ.equals(user.getR_id()));
            reqMap.put("isServer", !(Constants.ROLE_SJ.equals(user.getR_id()) || Constants.ROLE_CZ.equals(user.getR_id())));
            reqMap.put("s_id", user.getS_id());
        }
        List<Map<String, Object>> modelList = shangJiDao.getPublicCarInfo(reqMap);

        for (Map<String, Object> buyInfo : modelList) {
            // 对价格字段值做特别处理
            buyInfo.put("price", this.priceHandle(buyInfo));
        }
        resultMap.put("modelList", modelList);
		cachedThreadPool.execute(() -> {
		    if(reqMap.get("model")==null || reqMap.get("brand")==null){
		        return;
            }
			String model = reqMap.get("model").toString();
			String brand = reqMap.get("brand").toString();
			int price = (int) reqMap.get("price");
			if (!"".equals(model) || price != 0 || !"".equals(brand)) {
				logger.info("租售列表有筛选的搜索");
				insertUserBehavior(reqMap, Constants.BEHAVIOR_SALEANDRENT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_SEARCH.getBehavior(), user, device);
			} else {
				logger.info("进入租售列表加分");
				insertUserBehavior(reqMap, Constants.BEHAVIOR_SALEANDRENT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_LIST.getBehavior(), user, device);
			}
		});
        return resultMap;
    }


    /**
     * 获取设备出租详情
     */
    @Override
    public Map<String, Object> getPublicCarDetail(Map<String, Object> reqMap, User currentUser, String device) throws Exception {
        Map<String, Object> buyInfo = null;
        String id = reqMap.get("id").toString();
        //判断该数据是否在新机里
        int isNewMachine = shangJiMapper.isNewMachine(id);
        if(isNewMachine > 0){
            buyInfo = shangJiDao.getNewMachineDetail(reqMap);
            buyInfo.put("price", this.priceHandle(buyInfo));
            shangJiDao.updateNewMachineBrowser(buyInfo);
        }else {
            buyInfo = shangJiDao.getPublicCarDetail(reqMap);
            if (currentUser != null && buyInfo.get("subject") != null && buyInfo.get("create_user") != null) {
                String context = buyInfo.get("subject").toString();
                String receiver = buyInfo.get("create_user").toString();
                reqMap.put("context", context);
                reqMap.put("receive_user", receiver);
                reqMap.put("send_type", 10);
                reqMap.put("extra_params", "{\"push_liulan\":\"" + reqMap.get("id").toString() + "\"}");
                personalCenterService.pushVisitMessage(reqMap, currentUser, context);
        }
            // 对价格字段值做特别处理
            buyInfo.put("price", this.priceHandle(buyInfo));
            shangJiDao.updateBuyInfoBrowse(buyInfo);
            cachedThreadPool.execute(() -> {
                logger.info("获取租售详情加分");
                insertUserBehavior(reqMap, Constants.BEHAVIOR_SALEANDRENT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_DETAIL.getBehavior(), currentUser, device);
            });
        }

        return buyInfo;
    }

    private String priceHandle(Map<String, Object> buyInfo) {
        if (buyInfo.get("price") == null || StringUtils.isBlank(buyInfo.get("price").toString())) {
            return "面议";
        }
        String price = buyInfo.get("price").toString();
        if (price.contains("面议")) {
            return "面议";
        }
        try {
            if (price.contains("万")) {
                return price.substring(0, price.indexOf("万")).trim() + "万元";
            } else if (price.contains("元")) {
                return Double.valueOf(price.substring(0, price.indexOf("元")).trim()) / 10000 + "万元";
            } else {
                return Double.valueOf(price) / 10000 + "万元";
            }
        } catch (Exception e) {
            return "面议";
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> addPublicCarDetail(User user, Map<String, Object> reqMap) {
        String id = UuidUtil.get32UUID();
        reqMap.put("id", id);
        if (reqMap.get("image") != null && !reqMap.get("image").equals("")) {
            reqMap.put("imagefirst", (reqMap.get("image").toString().split(","))[0]);
        }
        Map<String, Object> map = new HashMap<>();
        String type = reqMap.get("type").toString();
        if(user != null) {
            isCompanyApply(user.getId(), reqMap);
        } else {
            reqMap.put("isCompany", '0');
        }

        reqMap.put("examine_flag", 0); // 审核标志 0:未审核  1:审核通过 2:审核不通过；暂时审核状态设置为 1
        // isFromOPS表示从后市场创建的求购信息，暂不需要审核
        if ("求购".equals(type) && reqMap.get("isFromOPS") != null) {
            reqMap.put("examine_flag", 1);
        }
        int result = shangJiDao.addPublicCarDetail(reqMap);

        // 添加租售和品牌id
        if ("出售".equals(type)) {
            Map<String, Object> params = new HashMap<>();
            params.put("id", UuidUtil.get32UUID());
            params.put("buyinfo_id", reqMap.get("id"));
            params.put("model_id", reqMap.get("model_id"));
            params.put("brand_id", reqMap.get("brand_id"));
            params.put("parent_model_id", reqMap.get("parent_model_id"));
            params.put("parent_brand_id", reqMap.get("parent_brand_id"));
            params.put("update_user", user == null ? "" : user.getId());
            shangJiMapper.addBrandAndModel(params);
        }
        String msg = "";
        if ("出售".equals(type)) {
            msg = "二手出售";
        } else if ("求购".equals(type)) {
            msg = "二手求购";
        } else if ("出租".equals(type)) {
            msg = "机械求租";
        } else if ("求租".equals(type)) {
            msg = "机械求租";
        }
        if (!"出售".equals(type)) {
            reqMap.put("classification", "");
        }

        // user == null 表示是从运营平台登陆操作的后市场的接口，用户表不一致
        if (user != null) {
            // 生成我的发布记录
            this.saveMyRelease(user.getId(), user.getUser_name(), id, type, reqMap.get("subject").toString());
            // 获取积分
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("id", "2");
            personalCenterService.completeTask(user, paramsMap);
            msg = user.getUser_name() + "发布了" + msg + "信息，请尽快审核";
            this.publishApPushpNoticeAssignPerson(msg, user.getId());
        }

        map.put("id", id);
        return map;
    }

    @Override
    @Async
    public void pushUser(User user, Map<String, Object> pushMap) {

        // 创建一个 resultMap 对象
        Map<String, Object> resultMap = new HashMap<>();

// 调用 shangJiMapper.selectBrand 方法，并将结果存储在查询结果变量中
        List<Map<String, Object>> queryResult = shangJiMapper.selectBrand(pushMap);

// 检查查询结果是否非空
        if (!queryResult.isEmpty()) {
            // 将查询结果的第一个元素（如果有多个结果）复制到 resultMap 中
            resultMap.putAll(queryResult.get(0));
        }
        if (pushMap.get("brand").equals(resultMap.get("brand")) && "求购".equals(resultMap.get("type")) && pushMap.get("model").equals(resultMap.get("model"))){
            //给发布求购的人发出售人信息
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put(PushConstants.KEY_PUSH_CHUSHOU, pushMap.get("id").toString());
            List<Map<String, Object>> phoneList = shangJiMapper.selectSell(pushMap);
            Set<Object> uniquePhoneNumbers = new HashSet<>();
            AtomicInteger outcome = new AtomicInteger();
            for (Map<String, Object> phoneRecord : phoneList) {
                Object phoneNumber = phoneRecord.get("phone");
                // 在这里对每个手机号进行处理
                // 检查是否已经获取过该手机号
                if (uniquePhoneNumbers.add(phoneNumber)) {
                    // 如果是新的手机号，进行处理
                    Map<String, Object> senderMap = new HashMap<>();
                    senderMap.put("push_user_id", user.getId());
                    senderMap.put("title", "出售信息");
                    senderMap.put("push_content", pushMap.get("brand").toString()+pushMap.get("model").toString()+"有人正在出售(联系方式："+phoneNumber+"),"+"点此查看详情>>>");
                    senderMap.put("create_user", user.getId());
                    // 推送消息并且保存推送信息
                    PushResult pushResultresult = jiGuangPushUtil.publishMessagePush(senderMap, PushConstants.KEY_PUSH_CHUSHOU, "", paramsMap, UuidUtil.get32UUID());
                    // 如果消息推送成功，则把保存消息并把该发布的消息设置为已发送(方便市场人员 区别处理)
                    outcome.addAndGet(pushResultresult == null ? 1 : 0);
                    if(pushResultresult != null && pushResultresult.statusCode == 0) {
                        senderMap.put("id", UuidUtil.get32UUID());
                        senderMap.put("user", user.getId());
                        senderMap.put("send_type", "21"); // 发送类型-求购信息发送
                        senderMap.put("context", senderMap.get("push_content"));
                        senderMap.put("extra_params", "{\"push_chushou\":\""+ pushMap.get("id").toString() +"\"}");
                        senderMap.put("receive_user", user.getId());
                        senderMap.put("s_id", resultMap.get("create_sid"));
                        senderMap.put("client","YD");
                        messageRecordDao.addMessageRecord(senderMap);

                        // 更新是否推送的标识
                        shangJiDao.updateZoweBuyinfoDetailForPushFlag(pushMap);
                    }
                }
            }


                Map<String, String> extraParamsMap = new HashMap<>();
                extraParamsMap.put(PushConstants.KEY_PUSH_QIUGOU, pushMap.get("id").toString());
                pushMap.put("s_id", resultMap.get("create_sid"));
                List<Map<String, Object>> guanliyuanList = shangJiMapper.selectSellAndBuy(pushMap);
                //List<Map<String, String>> guanliyuanList = appDao.getGuanliyuanMapList(pushMap);
                AtomicInteger result = new AtomicInteger();
                guanliyuanList.forEach(guanliyuanItem -> {
                    String guanliyuanUserId = (String) guanliyuanItem.get("id");

                    Map<String, Object> messageMap = new HashMap<>();
                    messageMap.put("push_user_id", guanliyuanUserId);
                    messageMap.put("title", "求购信息");
                    messageMap.put("push_content", pushMap.get("brand").toString()+pushMap.get("model").toString()+"有人正在求购(联系方式："+pushMap.get("phone").toString()+"),"+"点此查看详情>>>");
                    messageMap.put("create_user", user.getId());
                   // messageMap.put("push_user_id","bbc9aa19387b49f2a6103d402b7803ef");
                    // 推送消息并且保存推送信息
                    PushResult pushResultresult = jiGuangPushUtil.publishMessagePush(messageMap, PushConstants.KEY_PUSH_QIUGOU, "", extraParamsMap, UuidUtil.get32UUID());
                    // 如果消息推送成功，则把保存消息并把该发布的消息设置为已发送(方便市场人员 区别处理)
                    result.addAndGet(pushResultresult == null ? 1 : 0);
                    if(pushResultresult != null && pushResultresult.statusCode == 0) {
                        messageMap.put("id", UuidUtil.get32UUID());
                        messageMap.put("user", user.getId());
                        messageMap.put("send_type", "21"); // 发送类型-求购信息发送
                        messageMap.put("context", messageMap.get("push_content"));
                        messageMap.put("extra_params", "{\"push_qiugou\":\""+ pushMap.get("id").toString() +"\"}");
                        messageMap.put("receive_user", guanliyuanUserId);
                        messageMap.put("s_id", resultMap.get("create_sid"));
                        messageMap.put("client","YD");
                        messageRecordDao.addMessageRecord(messageMap);

                        // 更新是否推送的标识
                        shangJiDao.updateZoweBuyinfoDetailForPushFlag(pushMap);
                    }
                });
        }
        if (pushMap.get("brand").equals(resultMap.get("brand")) && "出售".equals(resultMap.get("type")) && pushMap.get("model").equals(resultMap.get("model"))){
            //给发布出售的人发求购人信息
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put(PushConstants.KEY_PUSH_QIUGOU, pushMap.get("id").toString());
            List<Map<String, Object>> phoneList = shangJiMapper.selectWantBuy(pushMap);
            Set<Object> uniquePhoneNumbers = new HashSet<>();
            AtomicInteger outcome = new AtomicInteger();
            for (Map<String, Object> phoneRecord : phoneList) {
                Object phoneNumber = phoneRecord.get("phone");
                // 在这里对每个手机号进行处理
                // 检查是否已经获取过该手机号
                if (uniquePhoneNumbers.add(phoneNumber)) {
                    // 如果是新的手机号，进行处理
                    Map<String, Object> senderMap = new HashMap<>();
                    senderMap.put("push_user_id", user.getId());
                    senderMap.put("title", "求购信息");
                    senderMap.put("push_content", pushMap.get("brand").toString()+pushMap.get("model").toString()+"有人正在求购(联系方式："+phoneNumber+"),"+"点此查看详情>>>");
                    senderMap.put("create_user", user.getId());
                    // 推送消息并且保存推送信息
                    PushResult pushResultresult = jiGuangPushUtil.publishMessagePush(senderMap, PushConstants.KEY_PUSH_QIUGOU, "", paramsMap, UuidUtil.get32UUID());
                    // 如果消息推送成功，则把保存消息并把该发布的消息设置为已发送(方便市场人员 区别处理)
                    outcome.addAndGet(pushResultresult == null ? 1 : 0);
                    if(pushResultresult != null && pushResultresult.statusCode == 0) {
                        senderMap.put("id", UuidUtil.get32UUID());
                        senderMap.put("user", user.getId());
                        senderMap.put("send_type", "21"); // 发送类型-求购信息发送
                        senderMap.put("context", senderMap.get("push_content"));
                        senderMap.put("extra_params", "{\"push_qiugou\":\""+ pushMap.get("id").toString() +"\"}");
                        senderMap.put("receive_user", user.getId());
                        senderMap.put("s_id", resultMap.get("create_sid"));
                        senderMap.put("client","YD");
                        messageRecordDao.addMessageRecord(senderMap);

                        // 更新是否推送的标识
                        shangJiDao.updateZoweBuyinfoDetailForPushFlag(pushMap);
                    }
                }
                }

            Map<String, String> extraParamsMap = new HashMap<>();
            extraParamsMap.put(PushConstants.KEY_PUSH_CHUSHOU, pushMap.get("id").toString());
            pushMap.put("s_id", resultMap.get("create_sid"));

          //  List<Map<String, String>> guanliyuanList = appDao.getGuanliyuanMapList(pushMap);
            AtomicInteger result = new AtomicInteger();
            List<Map<String, Object>> guanliyuanList = shangJiMapper.selectSellAndBuy(pushMap);
            guanliyuanList.forEach(guanliyuanItem -> {
                String guanliyuanUserId = (String) guanliyuanItem.get("id");

                Map<String, Object> messageMap = new HashMap<>();
                messageMap.put("push_user_id", guanliyuanUserId);
                messageMap.put("title", "出售信息");
                messageMap.put("push_content", pushMap.get("brand").toString()+pushMap.get("model").toString()+"有人正在出售(联系方式："+pushMap.get("phone").toString()+"),"+"点此查看详情>>>");
                messageMap.put("create_user", user.getId());
               // messageMap.put("push_user_id","bbc9aa19387b49f2a6103d402b7803ef");
                // 推送消息并且保存推送信息
                PushResult pushResultresult = jiGuangPushUtil.publishMessagePush(messageMap, PushConstants.KEY_PUSH_QIUGOU, "", extraParamsMap, UuidUtil.get32UUID());
                // 如果消息推送成功，则把保存消息并把该发布的消息设置为已发送(方便市场人员 区别处理)
                result.addAndGet(pushResultresult == null ? 1 : 0);
                if(pushResultresult != null && pushResultresult.statusCode == 0) {
                    messageMap.put("id", UuidUtil.get32UUID());
                    messageMap.put("user", user.getId());
                    messageMap.put("send_type", "21"); // 发送类型-求购信息发送
                    messageMap.put("context", messageMap.get("push_content"));
                    messageMap.put("extra_params", "{\"push_chushou\":\""+ pushMap.get("id").toString() +"\"}");
                    messageMap.put("receive_user", guanliyuanUserId);
                    messageMap.put("s_id", resultMap.get("create_sid"));
                    messageMap.put("client","YD");
                    messageRecordDao.addMessageRecord(messageMap);

                    // 更新是否推送的标识
                    shangJiDao.updateZoweBuyinfoDetailForPushFlag(pushMap);
                }
            });
        }
        if (pushMap.get("brand").equals(resultMap.get("brand")) && "出租".equals(resultMap.get("type")) && pushMap.get("model").equals(resultMap.get("model"))){
            //给发布出租的人发求租人信息
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put(PushConstants.KEY_PUSH_QIUZU, pushMap.get("id").toString());
            List<Map<String, Object>> phoneList = shangJiMapper.selectSeekingRent(pushMap);
            Set<Object> uniquePhoneNumbers = new HashSet<>();
            AtomicInteger outcome = new AtomicInteger();
            for (Map<String, Object> phoneRecord : phoneList) {
                Object phoneNumber = phoneRecord.get("phone");
                // 在这里对每个手机号进行处理
                // 检查是否已经获取过该手机号
                if (uniquePhoneNumbers.add(phoneNumber)) {
                    // 如果是新的手机号，进行处理
                    Map<String, Object> senderMap = new HashMap<>();
                    senderMap.put("push_user_id", user.getId());
                    senderMap.put("title", "求租信息");
                    senderMap.put("push_content", pushMap.get("brand").toString()+pushMap.get("model").toString()+"有人正在求租(联系方式："+phoneNumber+"),"+"点此查看详情>>>");
                    senderMap.put("create_user", user.getId());
                    // 推送消息并且保存推送信息
                    PushResult pushResultresult = jiGuangPushUtil.publishMessagePush(senderMap, PushConstants.KEY_PUSH_QIUGOU, "", paramsMap, UuidUtil.get32UUID());
                    // 如果消息推送成功，则把保存消息并把该发布的消息设置为已发送(方便市场人员 区别处理)
                    outcome.addAndGet(pushResultresult == null ? 1 : 0);
                    if(pushResultresult != null && pushResultresult.statusCode == 0) {
                        senderMap.put("id", UuidUtil.get32UUID());
                        senderMap.put("user", user.getId());
                        senderMap.put("send_type", "21"); // 发送类型-求购信息发送
                        senderMap.put("context", senderMap.get("push_content"));
                        senderMap.put("extra_params", "{\"push_qiuzu\":\""+ pushMap.get("id").toString() +"\"}");
                        senderMap.put("receive_user", user.getId());
                        senderMap.put("s_id", resultMap.get("create_sid"));
                        senderMap.put("client","YD");
                        messageRecordDao.addMessageRecord(senderMap);

                        // 更新是否推送的标识
                        shangJiDao.updateZoweBuyinfoDetailForPushFlag(pushMap);
                    }
                }
                }


            //给发布求租的人发送出租人信息
            Map<String, String> extraParamsMap = new HashMap<>();
            extraParamsMap.put(PushConstants.KEY_PUSH_CHUZU, pushMap.get("id").toString());
            pushMap.put("s_id", resultMap.get("create_sid"));
            List<Map<String, Object>> guanliyuanList = shangJiMapper.selectSellA(pushMap);
           // List<Map<String, String>> guanliyuanList = appDao.getGuanliyuanMapList(pushMap);
            AtomicInteger result = new AtomicInteger();
            guanliyuanList.forEach(guanliyuanItem -> {
                String guanliyuanUserId = (String) guanliyuanItem.get("id");

                Map<String, Object> messageMap = new HashMap<>();
                messageMap.put("push_user_id", guanliyuanUserId);
                messageMap.put("title", "出租信息");
                messageMap.put("push_content", pushMap.get("brand").toString()+pushMap.get("model").toString()+"有人正在出租(联系方式："+pushMap.get("phone").toString()+"),"+"点此查看详情>>>");
                messageMap.put("create_user", user.getId());
               // messageMap.put("push_user_id","bbc9aa19387b49f2a6103d402b7803ef");
                // 推送消息并且保存推送信息
                PushResult pushResultresult = jiGuangPushUtil.publishMessagePush(messageMap, PushConstants.KEY_PUSH_CHUZU, "", extraParamsMap, UuidUtil.get32UUID());
                // 如果消息推送成功，则把保存消息并把该发布的消息设置为已发送(方便市场人员 区别处理)
                result.addAndGet(pushResultresult == null ? 1 : 0);
                if(pushResultresult != null && pushResultresult.statusCode == 0) {
                    messageMap.put("id", UuidUtil.get32UUID());
                    messageMap.put("user", user.getId());
                    messageMap.put("send_type", "21"); // 发送类型-求购信息发送
                    messageMap.put("context", messageMap.get("push_content"));
                    messageMap.put("extra_params", "{\"push_chuzu\":\""+ pushMap.get("id").toString() +"\"}");
                    messageMap.put("receive_user", guanliyuanUserId);
                    messageMap.put("s_id", resultMap.get("create_sid"));
                    messageMap.put("client","YD");
                    messageRecordDao.addMessageRecord(messageMap);

                    // 更新是否推送的标识
                    shangJiDao.updateZoweBuyinfoDetailForPushFlag(pushMap);
                }
            });
        }
        if (pushMap.get("brand").equals(resultMap.get("brand")) && "求租".equals(resultMap.get("type")) && pushMap.get("model").equals(resultMap.get("model"))){
            //给发布求租的人发出租人信息
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put(PushConstants.KEY_PUSH_CHUZU, pushMap.get("id").toString());
            List<Map<String, Object>> phoneList = shangJiMapper.selectHire(pushMap);
            Set<Object> uniquePhoneNumbers = new HashSet<>();
            AtomicInteger outcome = new AtomicInteger();
            for (Map<String, Object> phoneRecord : phoneList) {
                Object phoneNumber = phoneRecord.get("phone");
                // 在这里对每个手机号进行处理
                // 检查是否已经获取过该手机号
                if (uniquePhoneNumbers.add(phoneNumber)) {
                    // 如果是新的手机号，进行处理
                    Map<String, Object> senderMap = new HashMap<>();
                    senderMap.put("push_user_id", user.getId());
                    senderMap.put("title", "出租信息");
                    senderMap.put("push_content", pushMap.get("brand").toString()+pushMap.get("model").toString()+"有人正在出租(联系方式："+phoneNumber+"),"+"点此查看详情>>>");
                    senderMap.put("create_user", user.getId());
                    // 推送消息并且保存推送信息
                    PushResult pushResultresult = jiGuangPushUtil.publishMessagePush(senderMap, PushConstants.KEY_PUSH_CHUZU, "", paramsMap, UuidUtil.get32UUID());
                    // 如果消息推送成功，则把保存消息并把该发布的消息设置为已发送(方便市场人员 区别处理)
                    outcome.addAndGet(pushResultresult == null ? 1 : 0);
                    if(pushResultresult != null && pushResultresult.statusCode == 0) {
                        senderMap.put("id", UuidUtil.get32UUID());
                        senderMap.put("user", user.getId());
                        senderMap.put("send_type", "21"); // 发送类型-求购信息发送
                        senderMap.put("context", senderMap.get("push_content"));
                        senderMap.put("extra_params", "{\"push_chuzu\":\""+ pushMap.get("id").toString() +"\"}");
                        senderMap.put("receive_user", user.getId());
                        senderMap.put("s_id", resultMap.get("create_sid"));
                        senderMap.put("client","YD");
                        messageRecordDao.addMessageRecord(senderMap);

                        // 更新是否推送的标识
                        shangJiDao.updateZoweBuyinfoDetailForPushFlag(pushMap);
                    }
                }
                }
            Map<String, String> extraParamsMap = new HashMap<>();
            extraParamsMap.put(PushConstants.KEY_PUSH_QIUZU, pushMap.get("id").toString());
            pushMap.put("s_id", resultMap.get("create_sid"));
            List<Map<String, Object>> guanliyuanList = shangJiMapper.selectHireA(pushMap);
           // List<Map<String, String>> guanliyuanList = appDao.getGuanliyuanMapList(pushMap);
            AtomicInteger result = new AtomicInteger();
            guanliyuanList.forEach(guanliyuanItem -> {
                String guanliyuanUserId = (String) guanliyuanItem.get("id");

                Map<String, Object> messageMap = new HashMap<>();
                messageMap.put("push_user_id", guanliyuanUserId);
                messageMap.put("title", "求租信息");
                messageMap.put("push_content", pushMap.get("brand").toString()+pushMap.get("model").toString()+"有人正在求租(联系方式："+pushMap.get("phone").toString()+"),"+"点此查看详情>>>");
                messageMap.put("create_user", user.getId());
               // messageMap.put("push_user_id","bbc9aa19387b49f2a6103d402b7803ef");
                // 推送消息并且保存推送信息
                PushResult pushResultresult = jiGuangPushUtil.publishMessagePush(messageMap, PushConstants.KEY_PUSH_QIUZU, "", extraParamsMap, UuidUtil.get32UUID());
                // 如果消息推送成功，则把保存消息并把该发布的消息设置为已发送(方便市场人员 区别处理)
                result.addAndGet(pushResultresult == null ? 1 : 0);
                if(pushResultresult != null && pushResultresult.statusCode == 0) {
                    messageMap.put("id", UuidUtil.get32UUID());
                    messageMap.put("user", user.getId());
                    messageMap.put("send_type", "21"); // 发送类型-求购信息发送
                    messageMap.put("context", messageMap.get("push_content"));
                    messageMap.put("extra_params", "{\"push_qiuzu\":\""+ pushMap.get("id").toString() +"\"}");
                    messageMap.put("receive_user", guanliyuanUserId);
                    messageMap.put("s_id", resultMap.get("create_sid"));
                    messageMap.put("client","YD");
                    messageRecordDao.addMessageRecord(messageMap);

                    // 更新是否推送的标识
                    shangJiDao.updateZoweBuyinfoDetailForPushFlag(pushMap);
                }
            });
        }
    }


    @Override
    public void updateBuyinfoPromotion(User user, Map<String, Object> map) {
        shangJiMapper.updateBuyinfoPromotion(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCarDetailExamineFlag(Map<String, Object> map) throws Exception {
        map.put("update_time", new Date());
        if (map.get("ids") == null || StringUtils.isBlank(map.get("ids").toString())) {
            map.put("isPcBatchCheck", true);
        }
        shangJiDao.updateCarDetailExamineFlag(map);
        return true;
    }

    @Override
    public boolean systemCheckData(Map<String, Object> map) throws Exception {
        map.put("update_time", new Date());
        if (map.get("hour") == null || StringUtils.isBlank(map.get("hour").toString())) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "参数错误");
        }

        List<Map<String, Object>> shopList = shangJiMapper.getNoShopExamine(map);
        shangJiDao.updateShopExamineFlag(map);
        jiGuangPushUtil.buyinfoPublishCheckMessagePush(this.checkPassBatchPushMessage(shopList, "shop"));

        List<Map<String, Object>> joberList = shangJiMapper.getNoJoberExamine(map);
        shangJiDao.updateJoberExamineFlag(map);
        jiGuangPushUtil.buyinfoPublishCheckMessagePush(this.checkPassBatchPushMessage(joberList, "jober"));

        List<Map<String, Object>> recruitList = shangJiMapper.getNoRecruitExamine(map);
        shangJiDao.updateRecruitExamineFlag(map);
        jiGuangPushUtil.buyinfoPublishCheckMessagePush(this.checkPassBatchPushMessage(recruitList, "recruit"));

        List<Map<String, Object>> buyinfoList = shangJiMapper.getNoCarDetailExamine(map);
        shangJiDao.updateCarDetailExamineFlag(map);
        jiGuangPushUtil.buyinfoPublishCheckMessagePush(this.checkPassBatchPushMessage(buyinfoList, "buyinfo"));
        return true;
    }


    private List<Map<String, Object>> checkPassBatchPushMessage(List<Map<String, Object>> list, String type) {
        List<Map<String, Object>> pushMessageList = new LinkedList<>();
        LocalDateTime nowTime = LocalDateTime.now();
        if ("shop".equals(type)) {
            for (Map<String, Object> item : list) {
                pushMessageList.add(this.pushMessagePublishCheckParams(item.get("create_user").toString(), DateUtil.formatTime(nowTime),
                        PushConstants.TEMPLATE_CHECK_SHOP_PASS, PushConstants.KEY_PUSH_SHOP, item.get("id").toString()));
            }
        } else if ("jober".equals(type)) {
            for (Map<String, Object> item : list) {
                pushMessageList.add(this.pushMessagePublishCheckParams(item.get("create_user").toString(), DateUtil.formatTime(nowTime),
                        PushConstants.TEMPLATE_CHECK_QIUZHI_PASS, PushConstants.KEY_PUSH_QIUZHI, item.get("id").toString()));
            }
        } else if ("recruit".equals(type)) {
            for (Map<String, Object> item : list) {
                pushMessageList.add(this.pushMessagePublishCheckParams(item.get("create_user").toString(), DateUtil.formatTime(nowTime),
                        PushConstants.TEMPLATE_CHECK_ZHAOPIN_PASS, PushConstants.KEY_PUSH_ZHAOPIN, item.get("id").toString()));
            }
        } else if ("buyinfo".equals(type)) {
            String content = "";
            for (Map<String, Object> item : list) {
                String typeName = item.get("type").toString();
                String key = PushConstants.KEY_PUSH_CHUSHOU;
                if (Constants.publish_type_chushou.equals(typeName)) {
                    content = PushConstants.TEMPLATE_CHECK_CHUSHOU_PASS;
                    key = PushConstants.KEY_PUSH_CHUSHOU;
                } else if (Constants.publish_type_chuzu.equals(typeName)) {
                    content = PushConstants.TEMPLATE_CHECK_CHUZU_PASS;
                    key = PushConstants.KEY_PUSH_CHUZU;
                } else if (Constants.publish_type_qiugou.equals(typeName)) {
                    content = PushConstants.TEMPLATE_CHECK_QIUGOU_PASS;
                    key = PushConstants.KEY_PUSH_QIUGOU;
                } else if (Constants.publish_type_qiuzu.equals(typeName)) {
                    content = PushConstants.TEMPLATE_CHECK_QIUZU_PASS;
                    key = PushConstants.KEY_PUSH_QIUZU;
                }
                if (!"".equals(content)) {
                    pushMessageList.add(this.pushMessagePublishCheckParams(item.get("create_user").toString(), DateUtil.formatTime(nowTime), content, key, item.get("id").toString()));
                }
            }
        }
        return pushMessageList;
    }

    @Override
    public HashMap<String, Object> getSystemCheckData(Map<String, Object> map) throws Exception {
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("shopList", shangJiMapper.getNoShopExamine(map));
        resultMap.put("joberList", shangJiMapper.getNoJoberExamine(map));
        resultMap.put("recruitList", shangJiMapper.getNoRecruitExamine(map));
        resultMap.put("buyinfoList", shangJiMapper.getNoCarDetailExamine(map));
        return resultMap;
    }

    /**
     * 推送通知指定人
     *
     * @param msg
     * @return
     */
    private String publishApPushpNoticeAssignPerson(String msg, String currentUserId) {
        return this.publishApPushpNotice("5cc34a1bf92044af93f3faf9fdc48df6", msg, currentUserId);
    }

    /**
     * 推送通知封装
     *
     * @param alias
     * @param msg
     * @return
     */
    private String publishApPushpNotice(String alias, String msg, String currentUserId) {
        // app端推送通知
        Map<String, Object> pushMessageMap = new HashMap<>(6);
        pushMessageMap.put("alias", alias);
        pushMessageMap.put("msg", msg);
        pushMessageMap.put("type", "2");
        pushMessageMap.put("code", "10000");
        pushMessageMap.put("current_user_id", currentUserId);
        return jiGuangPushUtil.pushCurrency(pushMessageMap);
    }

    @Override
    public List<Map<String, Object>> getPublicCarInfoByLonlat(Map<String, Object> reqMap) {
        // 将数据库由postgresql切换为mysql
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        reqMap.put("caraddress", "%" + reqMap.get("caraddress") + "%");
        // 计算经纬度并排序
        List<Map<String, Object>> modelList = shangJiDao.getPublicCarInfoByLatlong(reqMap);
        return modelList;
    }

    @Override
    public List<Map<String, Object>> getCarInfo(Map<String, Object> reqMap) throws Exception {

        if (reqMap.containsKey("user_id")) {

            if (StringUtils.isNotBlank(reqMap.get("user_id").toString())) {

                reqMap.put("vehicle_model_id", reqMap.get("id"));
                reqMap.put("record_id", UuidUtil.get32UUID());

                Map<String, Object> clickCountMap = shangJiMapper.selectClickCount(reqMap);

                if (clickCountMap == null) {

                    shangJiMapper.recordVehicleModel(reqMap);
                } else {

                    shangJiMapper.updateClickCount(reqMap);
                }
            }
        }

        List<Map<String, Object>> infoList = shangJiDao.getCarInfo(reqMap);
        List<Map<String, Object>> mouldList = shangJiDao.getMould(reqMap);
        List<Map<String, Object>> arr1 = new ArrayList<Map<String, Object>>();
        for (Map<String, Object> mould : mouldList) {
            Map<String, Object> json1 = new HashMap<String, Object>();
            json1.put("typeName", mould.get("param_name"));
            List<Map<String, Object>> arr2 = new ArrayList<Map<String, Object>>();
            for (Map<String, Object> info : infoList) {
                JSONObject json2 = new JSONObject();
                if (mould.get("id").equals(info.get("parent_id"))) {
                    json2.put("typeName", info.get("param_name"));
                    json2.put("typeValue", info.get("param_value"));
                    arr2.add(json2);
                }
            }
            json1.put("typeValue", arr2);
            arr1.add(json1);
        }
        return arr1;
    }

    @Override
    public List<Map<String, Object>> getClickCarHistory(Map<String, Object> reqMap) throws Exception {

        List<Map<String, Object>> result = null;

        if (StringUtils.isNotBlank(reqMap.get("user_id").toString())) {

            reqMap.put("vehicle_model_id", reqMap.get("id"));
            reqMap.put("record_id", UuidUtil.get32UUID());

            result = shangJiMapper.getClickCarHistory(reqMap);
        }

        return result;
    }

    @Override
    public List<Map<String, Object>> province(Map<String, Object> reqMap) {
        List<Map<String, Object>> list = this.shangJiDao.getProvinceByNumber(reqMap);
        return list;
    }

    @Override
    public List<Map<String, Object>> city(Map<String, Object> reqMap) {
        List<Map<String, Object>> list = this.shangJiDao.getCityByNumber(reqMap);
        return list;
    }

    @Override
    public List<Map<String, Object>> area(Map<String, Object> reqMap) {
        List<Map<String, Object>> list = this.shangJiDao.getAreaByNumber(reqMap);
        return list;
    }

    // 搜索商城列表
    @Override
    public Map<String, Object> getMallList(Map<String, Object> reqMap) {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        reqMap.put("model_name", "%" + reqMap.get("model_name") + "%");
        List<Map<String, Object>> modelList = shangJiDao.getMallList(reqMap);
        Integer total = shangJiDao.getMallListSize(reqMap);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("modelList", modelList);
        resultMap.put("total", total);
        return resultMap;
    }

    /**
     * 过滤无效图片
     *
     * @return
     */
    private List<Map<String, Object>> filterImage(List<Map<String, Object>> imageList) {
        List<Map<String, Object>> modelList = new LinkedList<Map<String, Object>>();
        URLAvailability filterUrl = new URLAvailability();
        // 循环过滤
        for (Map<String, Object> map : imageList) {
            URL url = filterUrl.isConnect(map.get("imagefirst").toString());
            if (url != null) {
                modelList.add(map);
            }
        }
        return modelList;
    }

    @Override
    public Map<String, Object> getNewsList(Map<String, Object> reqMap) {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        List<Map<String, Object>> newsList = shangJiDao.getNewsList(reqMap);
        int total = shangJiDao.getNewsListCount(reqMap);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("newsList", newsList);
        resultMap.put("total", total);
        return resultMap;
    }

    @Override
    public Map<String, Object> getNewsDetail(Map<String, Object> reqMap) {
        Map<String, Object> newsDetail = shangJiDao.getNewsDetail(reqMap);
        shangJiDao.updateBrowseForHotNews(newsDetail);
        return newsDetail;
    }

    @Override
    public List<Map<String, Object>> getModelList(Map<String, Object> reqMap) {
        return shangJiMapper.getModelList();
    }

    @Override
    public List<Map<String, Object>> getMechanicsType() throws MyException {
        //获取所有大类别
        List<Map<String, Object>> bigMechanicsType = shangJiDao.getBigMechanicsType();
        if (bigMechanicsType.size() == 0) {
            return new ArrayList<>();
        }
        //根据大类别id获取所有中类别
        List<String> ids = new ArrayList<>();
        for (Map<String, Object> map : bigMechanicsType) {
            ids.add(map.get("id").toString());
        }
        Map<String, Object> repMap = new HashMap<>();
        repMap.put("ids", ids);
        //中类别集合
        List<Map<String, Object>> subMechanicsType = shangJiDao.getSubMechanicsType(repMap);
        if (subMechanicsType.size() == 0) {
            return bigMechanicsType;
        }
        List<Map<String, Object>> typeList = new ArrayList<>();
        for (Map<String, Object> map : bigMechanicsType) {
            Map<String, Object> type = new HashMap<>();
            //用于存放子类别list
            List<Map<String, Object>> subTypeList = new ArrayList<>();
            for (Map<String, Object> subMap : subMechanicsType) {
                Map<String, Object> subType = new HashMap<>();
                //判断大类别与子类别有关系
                if (map.get("id").toString().equals(subMap.get("parent_id").toString())) {
                    subType.put("subType", subMap.get("type_name").toString());
                    subType.put("type_id", subMap.get("id").toString());
                    subTypeList.add(subType);
                }
            }
            type.put("bigType", map.get("type_name").toString());
            type.put("subTypeList", subTypeList);
            typeList.add(type);
        }
        return typeList;
    }

    @Override
    public List<Map<String, Object>> getSaleMechanicsType(Map<String, Object> reqMap) throws MyException {
        //获取所有中类别
        List<Map<String, Object>> mechanicsTypes = shangJiDao.getMechanicsType(reqMap);
        if (mechanicsTypes.size() == 0) {
            return new ArrayList<>();
        }
        List<String> ids = new ArrayList<>();
        for (Map<String, Object> map : mechanicsTypes) {
            ids.add(map.get("id").toString());
        }
        Map<String, Object> repMap = new HashMap<>();
        repMap.put("ids", ids);
        //取子机械类别  小类别集合
        List<Map<String, Object>> smallMechanicsType = shangJiDao.getSubMechanicsType(repMap);
        if (smallMechanicsType.size() == 0) {
            return mechanicsTypes;
        }
        List<Map<String, Object>> typeList = new ArrayList<>();
        for (Map<String, Object> map : mechanicsTypes) {
            Map<String, Object> type = new HashMap<>();
            //用于存放子类别list
            List<Map<String, Object>> smallTypeList = new ArrayList<>();
            for (Map<String, Object> smallMap : smallMechanicsType) {
                Map<String, Object> smallType = new HashMap<>();
                //判断大类别与子类别有关系
                if (map.get("id").toString().equals(smallMap.get("parent_id").toString())) {
                    smallType.put("small_type", smallMap.get("type_name").toString());
                    smallType.put("type_id", smallMap.get("id").toString());
                    smallTypeList.add(smallType);
                }
            }
            type.put("type_id", map.get("id").toString());
            type.put("type_name", map.get("type_name").toString());
            type.put("smallTypeList", smallTypeList);
            typeList.add(type);
        }
        return typeList;
    }

    @Override
    public Map<String, Object> getSaleMechanicsTypeClassify(Map<String, Object> reqMap) throws MyException {
        //返回结果
        Map<String, Object> resultMap = new HashMap<>();
        //获取所有中类别
        List<Map<String, Object>> mechanicsTypes = shangJiDao.getMechanicsType(reqMap);

        //根据首字母分类
        String az = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
        List<Map<String, Object>> initials = new ArrayList<>();
        if (mechanicsTypes.size() > 0) {
            for (int i = 0; i < az.length(); i++) {
                char c = az.charAt(i);
                Map<String, Object> initialsMap = new HashMap<>();
                List<Map<String, Object>> initialsList = new ArrayList<>();
                for (Map<String, Object> brandMap : mechanicsTypes) {
                    if (brandMap.get("initials").equals(String.valueOf(c))) {
                        initialsList.add(brandMap);
                    }
                }
                if (initialsList.size() > 0) {
                    initialsMap.put("name", c);
                    initialsMap.put("list", initialsList);
                    initials.add(initialsMap);
                }
            }
        }
        resultMap.put("initials", initials);
        // 返回很慢暂时去掉
        //resultMap.put("hotMechanicsTypes", shangJiMapper.getHotMechanicsModel());
        return resultMap;
    }

    @Override
    public Map<String, Object> getBrandAttribute(Map<String, Object> reqMap) throws MyException {
        //返回结果
        Map<String, Object> map = new HashMap<>();
        //获取品牌
        List<Map<String, Object>> brandList = shangJiDao.getBrandByTypeId(reqMap);
        //获取大属性名
        Map<String, Object> bigAttribute = shangJiDao.getBigAttributeByTypeId(reqMap);
        //获取子属性名
        List<Map<String, Object>> subAttributeList = shangJiDao.getSubAttribute(bigAttribute);
        map.put("brandList", brandList);
        map.put("attributeList", subAttributeList);
        return map;
    }

    @Override
    public Map<String, Object> getTypeBrandAttribute(Map<String, Object> reqMap) throws MyException {
        //返回结果
        Map<String, Object> map = new HashMap<>();
        //获取机型
        List<Map<String, Object>> modelList = shangJiDao.getModelBySubTypeId(reqMap);
        //获取品牌
        List<Map<String, Object>> brandList = shangJiDao.getBrandByTypeId(reqMap);
        //根据首字母分类
        String az = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
        List<Map<String, Object>> initials = new ArrayList<>();
        if (brandList.size() > 0) {
            for (int i = 0; i < az.length(); i++) {
                char c = az.charAt(i);
                Map<String, Object> initialsMap = new HashMap<>();
                List<Map<String, Object>> initialsList = new ArrayList<>();
                for (Map<String, Object> brandMap : brandList) {
                    if (brandMap.get("initials").equals(String.valueOf(c))) {
                        initialsList.add(brandMap);
                    }
                }
                if (initialsList.size() > 0) {
                    initialsMap.put("name", c);
                    initialsMap.put("list", initialsList);
                    initials.add(initialsMap);
                }
            }
        }
        //获取大属性名
        Map<String, Object> bigAttribute = shangJiDao.getBigAttributeByTypeId(reqMap);
        //获取子属性名
        List<Map<String, Object>> subAttributeList = shangJiDao.getSubAttribute(bigAttribute);
        //获取热门品牌
        List<Map<String, Object>> hotBrandList = shangJiDao.getHotBrand();

        map.put("modelList", modelList);
        //map.put("brandList", brandList);
        map.put("initials", initials);
        map.put("bigAttribute", bigAttribute);
        map.put("subAttributeList", subAttributeList);
        map.put("hotBrand", hotBrandList);
        return map;
    }

    @Override
    public Map<String, Object> getMechanics(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        List<Map<String, Object>> list = shangJiDao.getMechanics(reqMap);
        int count = shangJiDao.getCountMechanics(reqMap);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("count", count);
        return map;
    }

    @Override
    public Map<String, Object> getInquiryInfo(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> map = new HashMap<>();
        //查询此机械的询底价信息
        List<Map<String, Object>> inquiryInfo = shangJiDao.getInquiryInfo(reqMap);
        //查询此机械的询底价人数
        Integer inquiryInfoCount = shangJiDao.getInquiryInfoCount(reqMap);
        map.put("inquiryInfo", inquiryInfo);
        map.put("inquiryInfoCount", inquiryInfoCount);
        return map;
    }

    @Override
    public int insertInquiry(Map<String, Object> reqMap) throws MyException {
        reqMap.put("id", UuidUtil.get32UUID());
        reqMap.put("delete_flag", 0);
        int inquiryResult = shangJiDao.insertInquiry(reqMap);
        //查询此机械的询底价人数
        Integer inquiryInfoCount = shangJiDao.getInquiryInfoCount(reqMap);
        inquiryInfoCount++;
        reqMap.put("inquiryInfoCount", inquiryInfoCount);
        //更新访问次数
        int updateResult = shangJiDao.updateInquiryInfoCount(reqMap);
        if (inquiryResult == 0 || updateResult == 0) {
            throw new MyException(Constants.CODE_ERROR, "新增失败");
        }
        return updateResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> insertMyCollection(User currentUser, Map<String, Object> reqMap, String device) throws MyException {
        List<Map<String, Object>> myCollections = shangJiDao.getMyCollection(reqMap);
        if (myCollections.size() > 0) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "业务操作失败");
        }
        String id = UuidUtil.get32UUID();
        reqMap.put("id", id);
        reqMap.put("delete_flag", 0);
        int insertResult = shangJiDao.insertMyCollection(reqMap);
        Map<String, Object> collectionMap = shangJiDao.collectionMap(reqMap);
        //推送给相应用户
        // 创建一个 resultMap 对象
        if ("出租".equals(reqMap.get("type"))) {
        Map<String, String> extraParamsMap = new HashMap<>();
        extraParamsMap.put(PushConstants.KEY_PUSH_QIUGOU, reqMap.get("id").toString());

        List<Map<String, String>> guanliyuanList = appDao.getGuanliyuanMapList(reqMap);
        guanliyuanList.forEach(guanliyuanItem -> {
            String guanliyuanUserId = guanliyuanItem.get("id");

            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("push_user_id", guanliyuanUserId);
            messageMap.put("title", "收藏信息");
            messageMap.put("push_content", "(" + reqMap.get("u_name").toString() + ")(" + reqMap.get("mobile_phone").toString() + ")已收藏您发布的出租信息，请查看>>>");
            messageMap.put("create_user", currentUser.getId());

            // 推送消息并且保存推送信息
            PushResult pushResultresult = jiGuangPushUtil.publishMessagePush(messageMap, PushConstants.KEY_PUSH_QIUGOU, "", extraParamsMap, UuidUtil.get32UUID());

        });
        if (collectionMap.get("subject") != null && collectionMap.get("publish_user") != null) {
            String context = collectionMap.get("subject").toString();
            String receiver = collectionMap.get("publish_user").toString();
            //reqMap.put("context", context);
            reqMap.put("context", "(" + reqMap.get("u_name").toString() + ")(" + reqMap.get("mobile_phone").toString() + ")已收藏您发布的出租信息，请查看>>>");
            reqMap.put("receive_user", receiver);
            reqMap.put("send_type", 11);
            reqMap.put("extra_params", "{\"push_shoucang\":\"" + reqMap.get("id").toString() + "\"}");
            personalCenterService.pushVisitMessage(reqMap, currentUser, context);
        }
    }if ("出售".equals(reqMap.get("type"))) {
        Map<String, String> extraParamsMap = new HashMap<>();
        extraParamsMap.put(PushConstants.KEY_PUSH_QIUGOU, reqMap.get("id").toString());

        List<Map<String, String>> guanliyuanList = appDao.getGuanliyuanMapList(reqMap);
        guanliyuanList.forEach(guanliyuanItem -> {
            String guanliyuanUserId = guanliyuanItem.get("id");

            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("push_user_id", guanliyuanUserId);
            messageMap.put("title", "收藏信息");
            messageMap.put("push_content",  reqMap.get("u_name").toString() + "(" + reqMap.get("mobile_phone").toString() + ")已收藏您发布的出售信息，请查看>>>");
            messageMap.put("create_user", currentUser.getId());

            // 推送消息并且保存推送信息
            PushResult pushResultresult = jiGuangPushUtil.publishMessagePush(messageMap, PushConstants.KEY_PUSH_QIUGOU, "", extraParamsMap, UuidUtil.get32UUID());

        });
        if (collectionMap.get("subject") != null && collectionMap.get("publish_user") != null) {
            String context = collectionMap.get("subject").toString();
            String receiver = collectionMap.get("publish_user").toString();
            //reqMap.put("context", context);
            reqMap.put("context",  reqMap.get("u_name").toString() + "(" + reqMap.get("mobile_phone").toString() + ")已收藏您发布的出售信息，请查看>>>");
            reqMap.put("receive_user", receiver);
            reqMap.put("send_type", 11);
            reqMap.put("extra_params", "{\"push_shoucang\":\"" + reqMap.get("id").toString() + "\"}");
            personalCenterService.pushVisitMessage(reqMap, currentUser, context);
        }
    }
        if (insertResult == 0) {
            throw new MyException(Constants.CODE_ERROR, "新增失败");
        }
        // 获取积分
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id", 3);
        //完成任务
        personalCenterService.completeTask(currentUser, paramsMap);
        Map<String, Object> map = new HashMap<>();
        map.put("id", reqMap.get("o_id").toString());

		cachedThreadPool.execute(() -> {
			//收藏行为加分
			logger.info("收藏加分");
			String type = reqMap.get("type").toString();
			collectBehavior(reqMap, type, currentUser, device);
		});


        return map;
    }

    /**
     * 收藏加分
     *
     * @param reqMap
     * @param type
     * @param currentUser
     * @param device
     */
    public void collectBehavior(Map<String, Object> reqMap, String type, User currentUser, String device) {
        logger.info(type + "收藏加分");
        if ("招标".equals(type) || "中标".equals(type)) {
            insertUserBehavior(reqMap, Constants.BEHAVIOR_BID_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_COLLECT.getBehavior(), currentUser, device);
        } else if ("企业招聘".equals(type) || "个人求职".equals(type)) {
            insertUserBehavior(reqMap, Constants.BEHAVIOR_RECRUIT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_COLLECT.getBehavior(), currentUser, device);
        } else if ("出售".equals(type) || "出租".equals(type)) {
            insertUserBehavior(reqMap, Constants.BEHAVIOR_SALEANDRENT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_COLLECT.getBehavior(), currentUser, device);
        } else if ("维修服务".equals(type)) {
            insertUserBehavior(reqMap, Constants.BEHAVIOR_SHOP_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_COLLECT.getBehavior(), currentUser, device);
        }
    }

    @Override
    public int deleteMyCollection(Map<String, Object> reqMap) throws MyException {
        //取o_id集合
        List<String> idList = (List<String>) reqMap.get("id");

        //用于计算删除的个数
        int count = 0;
        for (String id : idList) {
            Map<String, Object> map = new HashMap<>();
            map.put("o_id", id);
            map.put("u_id", reqMap.get("u_id").toString());
            int result = shangJiDao.deleteMyCollection(map);
            count++;
        }
        if (count == idList.size()) {
            return count;
        } else {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "操作失败");
        }
    }

    @Override
    public Map<String, Object> getMyCollection(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> map = new HashMap<>(16);
        List<Map<String, Object>> myCollections = shangJiDao.getMyCollection(reqMap);
        map.put("myCollection", myCollections);
        return map;
    }

    @Override
    public Map<String, Object> myCollectionSearch(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));

        List<Map<String, Object>> myCollections = shangJiDao.myCollectionSearch(reqMap);
        List<String> shopIds = new ArrayList<>();
        List<String> chuzuIds = new ArrayList<>();
        List<String> chushouIds = new ArrayList<>();
        List<String> qiuzuIds = new ArrayList<>();
        List<String> qiugouIds = new ArrayList<>();
        List<String> zhaobiaoIds = new ArrayList<>();
        List<String> zhongbiaoIds = new ArrayList<>();
        List<String> recruitIds = new ArrayList<>();
        List<String> joberIds = new ArrayList<>();
        for (Map<String, Object> myCollection : myCollections) {
            String type = myCollection.get("type").toString();
            String id = myCollection.get("o_id").toString();
            if ("维修服务".equals(type)) {
                shopIds.add(id);
            } else if ("出租".equals(type)) {
                chuzuIds.add(id);
            } else if ("求租".equals(type)) {
                qiuzuIds.add(id);
            } else if ("出售".equals(type)) {
                chushouIds.add(id);
            } else if ("求购".equals(type)) {
                qiugouIds.add(id);
            } else if ("招标".equals(type)) {
                zhaobiaoIds.add(id);
            } else if ("中标".equals(type)) {
                zhongbiaoIds.add(id);
            } else if ("企业招聘".equals(type)) {
                recruitIds.add(id);
            } else if ("个人求职".equals(type)) {
                joberIds.add(id);
            }
        }
        Map<String, Object> map = new HashMap<>(16);
        List<Map<String, Object>> listMap = new ArrayList<>();
        if (shopIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "publish_shop_info");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(shopIds, reqMap);
            mapList.put("type", "维修服务");
            mapList.put("list", list);
            listMap.add(mapList);
        }
        if (chuzuIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "zowe_buyinfo_detail");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(chuzuIds, reqMap);
            mapList.put("type", "出租");
            mapList.put("list", list);
            listMap.add(mapList);
        }
        if (qiuzuIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "zowe_buyinfo_detail");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(qiuzuIds, reqMap);
            mapList.put("type", "求租");
            mapList.put("list", list);
            listMap.add(mapList);
        }
        if (chushouIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "zowe_buyinfo_detail");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(chushouIds, reqMap);
            mapList.put("type", "出售");
            mapList.put("list", list);
            listMap.add(mapList);
        }
        if (qiugouIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "zowe_buyinfo_detail");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(qiugouIds, reqMap);
            mapList.put("type", "求购");
            mapList.put("list", list);
            listMap.add(mapList);
        }
        if (zhaobiaoIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "zowe_project");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(zhaobiaoIds, reqMap);
            mapList.put("type", "招标");
            mapList.put("list", list);
            listMap.add(mapList);
        }
        if (zhongbiaoIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "zowe_project");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(zhongbiaoIds, reqMap);
            mapList.put("type", "中标");
            mapList.put("list", list);
            listMap.add(mapList);
        }
        if (recruitIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "publish_recruit_info");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(recruitIds, reqMap);
            mapList.put("type", "企业招聘");
            mapList.put("list", list);
            listMap.add(mapList);
        }
        if (joberIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "publish_jober_info");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(joberIds, reqMap);
            mapList.put("type", "个人求职");
            mapList.put("list", list);
            listMap.add(mapList);
        }
        map.put("myCollection", listMap);
        return map;
    }

    @Override
    public Map<String, Object> getTypeMyCollection(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        Map<String, Object> map = new HashMap<>(16);
        Integer count = shangJiDao.getMyCollectionCount(reqMap);
        map.put("count", count);

        List<Map<String, Object>> myCollections = shangJiDao.getTypeMyCollection(reqMap);
        if (myCollections.size() == 0) {
            map.put("myCollection", myCollections);
            return map;
        }
        List<String> ids = new ArrayList<>();
        for (Map<String, Object> myCollection : myCollections) {
            ids.add(myCollection.get("o_id").toString());
        }
        List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(ids, reqMap);
        map.put("myCollection", list);
        return map;
    }

    @Override
    public List<Map<String, Object>> getMyCollectionType(Map<String, Object> reqMap) throws MyException {
        List<Map<String, Object>> collectionTypes = shangJiMapper.getMyCollectionType(reqMap);
        for (Map<String, Object> collectionType : collectionTypes) {
            String type = collectionType.get("type").toString();
            if ("出租".equals(type) || "求租".equals(type)) {
                collectionType.put("type", "机械出租");
            }
            if ("出售".equals(type) || "求购".equals(type)) {
                collectionType.put("type", "二手出售");
            }
            if ("招标".equals(type) || "中标".equals(type)) {
                collectionType.put("type", "招中标");
            }
        }
        return collectionTypes;
    }

    @Override
    public Map<String, Object> getMyCollectionId(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> map = new HashMap<>(16);
        List<String> oids = shangJiMapper.getMyCollectionId(reqMap);
        map.put("o_id", oids);
        return map;
    }

    @Override
    public int addMycollectionSearchRecord(Map<String, Object> reqMap) throws MyException {
        int count = shangJiMapper.getSearchRecordByName(reqMap);
        if (count > 0) {
            return 1;
        }
        reqMap.put("id", UuidUtil.get32UUID());
        //新增
        int result = shangJiMapper.addMycollectionSearchRecord(reqMap);
        return result;
    }

    @Override
    public Map<String, Object> getMycollectionSearchRecord(Map<String, Object> reqMap) throws MyException {
        //默认获取最新的前10条
        List<Map<String, Object>> list = shangJiMapper.getMycollectionSearchRecord(reqMap);
        Map<String, Object> map = new HashMap<>(16);
        map.put("list", list);
        return map;
    }

    @Override
    public int delMycollectionSearchRecord(Map<String, Object> reqMap) {
        //删除
        int result = shangJiMapper.delMycollectionSearchRecord(reqMap);
        return result;
    }

    @Override
    public Map<String, Object> getTypeConfigure(Map<String, Object> reqMap) throws MyException {
        List<Map<String, Object>> typeConfigure = shangJiMapper.getTypeConfigure(reqMap);
        Map<String, Object> map = new HashMap<>(16);
        map.put("type", typeConfigure);
        return map;
    }

    @Override
    public int insertTypeConfigure(Map<String, Object> reqMap) throws MyException {
        reqMap.put("id", UuidUtil.get32UUID());
        int result = shangJiMapper.insertTypeConfigure(reqMap);
        if (result == 0) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "新增失败");
        }
        return result;
    }

    @Override
    public int updateRecentVisitCity(Map<String, Object> reqMap) throws MyException {
        //查询数据库最近访问城市中有没有这条城市的记录
        Map<String, Object> visitCityMap = shangJiMapper.getVisitCityByCity(reqMap);
        if (visitCityMap != null) {
            reqMap.put("id", visitCityMap.get("id").toString());
            reqMap.put("update_time", new Date());
            //reqMap.put("city", "");
            //修改 修改时间
            int result = shangJiMapper.updateVisitCity(reqMap);
            return 1;
        }
        //查询这个用户下有几个最近访问城市
        int count = shangJiMapper.getVisitCityCountByUid(reqMap);
        if (count < 3) {
            reqMap.put("id", UuidUtil.get32UUID());
            //新增
            int result = shangJiMapper.insertVisitCity(reqMap);
            return result;
        } else {
            //取数据库访问城市最早的一条记录
            Map<String, Object> map = shangJiMapper.getVisitCityByTime(reqMap);
            reqMap.put("id", map.get("id").toString());
            reqMap.put("update_time", new Date());
            //修改 修改时间
            int result = shangJiMapper.updateVisitCity(reqMap);
            return result;
        }
    }

    @Override
    public Map<String, Object> getRecentVisitCity(Map<String, Object> reqMap) throws MyException {
        List<Map<String, Object>> visitCitys = shangJiMapper.getRecentVisitCity(reqMap);
        Map<String, Object> map = new HashMap<>(16);
        map.put("visitCitys", visitCitys);
        return map;
    }

    @Override
    public Map<String, Object> getMyRelease(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        List<Map<String, Object>> myReleases = shangJiMapper.getMyRelease(reqMap);
        Integer count = shangJiMapper.getMyReleaseCount(reqMap);
        Map<String, Object> map = new HashMap<>(16);
        map.put("myReleases", myReleases);
        map.put("count", count);
        return map;
    }

    @Override
    public boolean saveMyRelease(String uId, String uName, String oId, String type, String subject) {
        Map<String, Object> paramsMap = new HashMap<>(10);
        paramsMap.put("id", UuidUtil.get32UUID());
        paramsMap.put("u_id", uId);
        paramsMap.put("u_name", uName);
        paramsMap.put("o_id", oId);
        paramsMap.put("type", type);
        paramsMap.put("subject", subject);
        return shangJiMapper.saveMyRelease(paramsMap) > 1;
    }

    @Override
    public Map<String, Object> getMyReleaseNew(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        if ("新机".equals(reqMap.get("type").toString())) {
//            reqMap.put("type", Constants.publish_type_chushou);
//            reqMap.put("isNew", true);
        } else if (Constants.publish_type_chushou.equals(reqMap.get("type").toString())) {
            reqMap.put("isNew", false);
        }
        String type = reqMap.get("type").toString();
        int count;
        if (Constants.publish_type_zhaopin.equals(type)) {
            count = shangJiMapper.getMyReleaseSearchCount(reqMap, "publish_recruit_info", type);
        } else if (Constants.publish_type_qiuzhi.equals(type)) {
            count = shangJiMapper.getMyReleaseSearchCount(reqMap, "publish_jober_info", type);
        } else if (Constants.publish_type_weixiu.equals(type)) {
            count = shangJiMapper.getMyReleaseSearchCount(reqMap, "publish_shop_info", type);
        } else if (Constants.publish_type_new_machine.equals(type)){
            count = shangJiMapper.getNewMachineCount(reqMap);
        } else {
            count = shangJiMapper.getMyReleaseSearchCount(reqMap, "zowe_buyinfo_detail", type);
        }
        List<Map<String, Object>> myReleases = null;
        if ("新机".equals(reqMap.get("type").toString())) {
            myReleases = shangJiMapper.getNewMachineRelease(reqMap);
        }else{
            myReleases = shangJiMapper.getMyReleaseNew(reqMap);
        }

        List<Map<String, Object>> myReleaseList = new LinkedList<>();
        for (Map<String, Object> releaseMap : myReleases) {
            String type1 = releaseMap.get("type").toString();
            if("新机".equals(reqMap.get("type").toString())){
                type1 = "新机";
            }
            if (Constants.publish_type_zhaopin.equals(type1)) {
                if (shangJiMapper.getMyReleaseById("publish_recruit_info", releaseMap.get("o_id").toString(), reqMap) != null) {
                    myReleaseList.add(shangJiMapper.getMyReleaseById("publish_recruit_info", releaseMap.get("o_id").toString(), reqMap));
                }
            } else if (Constants.publish_type_qiuzhi.equals(type1)) {
                if (shangJiMapper.getMyReleaseById("publish_jober_info", releaseMap.get("o_id").toString(), reqMap) != null) {
                    myReleaseList.add(shangJiMapper.getMyReleaseById("publish_jober_info", releaseMap.get("o_id").toString(), reqMap));
                }
            } else if (Constants.publish_type_weixiu.equals(type1)) {
                if (shangJiMapper.getMyReleaseById("publish_shop_info", releaseMap.get("o_id").toString(), reqMap) != null) {
                    myReleaseList.add(shangJiMapper.getMyReleaseById("publish_shop_info", releaseMap.get("o_id").toString(), reqMap));
                }
            } else if (Constants.publish_type_chushou.equals(type1)||Constants.publish_type_chuzu.equals(type1)||Constants.publish_type_qiugou.equals(type1)||Constants.publish_type_qiuzu.equals(type1)){
                if (shangJiMapper.getMyReleaseById("zowe_buyinfo_detail", releaseMap.get("o_id").toString(), reqMap) != null) {
                    myReleaseList.add(shangJiMapper.getMyReleaseById("zowe_buyinfo_detail", releaseMap.get("o_id").toString(), reqMap));
                }
            } else {
                if (shangJiMapper.getMyReleaseById("t_s_ss_new_machine", releaseMap.get("o_id").toString(), reqMap) != null) {
                    myReleaseList.add(shangJiMapper.getMyReleaseById("t_s_ss_new_machine", releaseMap.get("o_id").toString(), reqMap));
                }
            }
        }
        Map<String, Object> map = new HashMap<>(3);
        map.put("myReleases", myReleaseList);
        map.put("count", count);
        return map;
    }


    @Override
    public Map<String, Object> myReleaseSearch(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        List<Map<String, Object>> myReleaseSearchs = shangJiMapper.myReleaseSearch(reqMap);
        List<String> shopIds = new ArrayList<>();
        List<String> chuzuChushouIds = new ArrayList<>();
        List<String> qiuzuQiugouIds = new ArrayList<>();
        List<String> recruitIds = new ArrayList<>();
        List<String> joberIds = new ArrayList<>();
        for (Map<String, Object> myReleaseSearch : myReleaseSearchs) {
            String type = myReleaseSearch.get("type").toString();
            String id = myReleaseSearch.get("id").toString();
            if ("维修服务".equals(type)) {
                shopIds.add(id);
            } else if ("出租出售".equals(type)) {
                chuzuChushouIds.add(id);
            } else if ("求租求购".equals(type)) {
                qiuzuQiugouIds.add(id);
            } else if ("企业招聘".equals(type)) {
                recruitIds.add(id);
            } else if ("个人求职".equals(type)) {
                joberIds.add(id);
            }
        }
        Map<String, Object> map = new HashMap<>(16);
        List<Map<String, Object>> listMap = new ArrayList<>();
        if (shopIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "publish_shop_info");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(shopIds, reqMap);
            mapList.put("list", list);
            mapList.put("type", "维修服务");
            listMap.add(mapList);
        }
        if (chuzuChushouIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "zowe_buyinfo_detail");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(chuzuChushouIds, reqMap);
            mapList.put("type", "出租出售");
            mapList.put("list", list);
            listMap.add(mapList);
        }
        if (qiuzuQiugouIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "zowe_buyinfo_detail");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(qiuzuQiugouIds, reqMap);
            mapList.put("type", "求租求购");
            mapList.put("list", list);
            listMap.add(mapList);
        }
        if (recruitIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "publish_recruit_info");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(recruitIds, reqMap);
            mapList.put("list", list);
            mapList.put("type", "企业招聘");
            listMap.add(mapList);
        }
        if (joberIds.size() > 0) {
            Map<String, Object> mapList = new HashMap<>(16);
            reqMap.put("table_name", "publish_jober_info");
            List<Map<String, Object>> list = shangJiMapper.getTableIdMyCollection(joberIds, reqMap);
            mapList.put("list", list);
            mapList.put("type", "个人求职");
            listMap.add(mapList);
        }
        map.put("myReleaseSearchs", listMap);
        return map;
    }

    @Override
    public Map<String, Object> getHotCity() throws MyException {
        List<Map<String, Object>> hotCitys = shangJiMapper.getHotCity();
        Map<String, Object> map = new HashMap<>(16);
        map.put("hotCitys", hotCitys);
        return map;
    }

    @Override
    public Map<String, Object> getMyReleaseId(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> map = new HashMap<>(16);
        List<String> ids = shangJiMapper.getMyReleaseId(reqMap);
        map.put("id", ids);
        return map;
    }

    @Override
    public int deleteMyRelease(Map<String, Object> reqMap) throws MyException {
        //取id集合
        List<String> idList = (List<String>) reqMap.get("id");
        if (idList.size() > 0) {
            shangJiMapper.updateMyRelease(idList, reqMap);
            shangJiMapper.deleteMyRelease(idList, reqMap.get("u_id").toString(),reqMap.get("r_id").toString());
        }
        return 1;
    }

    //boolean activitySignIn(String user_id) throws MyException;


    @Override
    public Map<String, Object> getActivitySignInByUserId(String userId) throws MyException {
        Map<String, Object> reqQuery = new HashMap<>(3);
        Map<String, Object> data = new HashMap<>(3);
        reqQuery.put("user_id", userId);
        Map<String, Object> lastData = shangJiMapper.selectSignIn(reqQuery);
        if (lastData == null) {
            data.put("signIn_count", 0);
            data.put("draws_count", 0);
        } else {
            LocalDate currentDate = LocalDate.now();
            LocalDate yesterdayDate = currentDate.minusDays(1);
            LocalDate signInTime = LocalDate.parse(lastData.get("signIn_time").toString().substring(0, 10));
            if (yesterdayDate.equals(signInTime) || currentDate.equals(signInTime)) {
                data.put("signIn_count", lastData.get("signIn_count"));
                if (currentDate.equals(signInTime)) {
                    data.put("status", true);
                }
            } else {
                data.put("signIn_count", 0);
            }
            data.put("draws_count", lastData.get("draws_count"));
        }
        data.putIfAbsent("status", false);
        return data;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> activitySignIn(User currentUser, Map<String, Object> reqMap) throws MyException {
        Map<String, Object> responseData = new HashMap<>(9);
        // 默认值
        int signInCount = 1, drawsCount = 0;
        // 查询上次签到数据
        Map<String, Object> lastData = shangJiMapper.selectSignIn(reqMap);
        // 如果lastDat为null，为第一次签到
        if (lastData == null) {
            this.insertSignIn(reqMap.get("user_id").toString(), signInCount, drawsCount);
        } else {
            LocalDate currentDate = LocalDate.now();
            LocalDate yesterdayDate = currentDate.minusDays(1);
            LocalDate signInTime = LocalDate.parse(lastData.get("signIn_time").toString().substring(0, 10));
            // 获取剩余抽奖次数
            drawsCount = (Integer) lastData.get("draws_count");
            // 已经签到次数
            signInCount = (Integer) lastData.get("signIn_count");
            if (currentDate.equals(signInTime)) {
                // 如果上次签到日期是当前日期，则返回true
                responseData.put("signIn_count", 0);
                responseData.put("draws_count", 0);
                responseData.put("status", false);
                return responseData;
            } else if (yesterdayDate.equals(signInTime)) {
                // 连续签到
                // 如果上次签到次数为6次，则这次抽奖次数加1
                if (signInCount % 7 == 6) {
                    drawsCount++;
                }
                this.insertSignIn(reqMap.get("user_id").toString(), ++signInCount, drawsCount);
            } else {
                // 非连续签到
                signInCount = 1;
                this.insertSignIn(reqMap.get("user_id").toString(), signInCount, drawsCount);
            }
            // 上条记录的delete_flag置为1
            shangJiMapper.logicDeleteSignIn(lastData.get("id").toString());
        }
        // 获取积分
        reqMap.put("signIn_count", signInCount);
        reqMap.put("id", 6);
        personalCenterService.completeTask(currentUser, reqMap);
        responseData.put("signIn_count", signInCount);
        responseData.put("draws_count", drawsCount);
        responseData.put("status", true);
        return responseData;
    }

    /**
     * 封装签到插入数据代码
     *
     * @param userId
     * @param signInCount
     * @param drawsCount
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertSignIn(String userId, int signInCount, int drawsCount) {
        Map<String, Object> dataMap = new HashMap<>(6);
        dataMap.put("id", UuidUtil.get32UUID());
        dataMap.put("user_id", userId);
        dataMap.put("signIn_count", signInCount);
        dataMap.put("draws_count", drawsCount);
        shangJiMapper.insertSignIn(dataMap);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> activitySignInPrize(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> responseData = new HashMap<>(3);
        responseData.put("contact_phoneNum", "");
        responseData.put("contact_name", "");
        responseData.put("address", "");
        // 签到表的剩余抽奖次数减1
        Map<String, Object> lastData = shangJiMapper.selectSignIn(reqMap);
        if (lastData == null) {
            responseData.put("status", false);
            responseData.put("draws_count", 0);
            return responseData;
        }
        // 如果没有抽奖次数，则返回
        int drawsCount = (Integer) lastData.get("draws_count");
        if (drawsCount <= 0) {
            responseData.put("status", false);
            responseData.put("draws_count", 0);
            return responseData;
        }
        lastData.put("draws_count", --drawsCount);
        shangJiMapper.updateDrawsCountSignIn(lastData);

        reqMap.put("hasContactInfo", true);
        // 抽奖奖品
        reqMap.put("type", 1);
        List<Map<String, Object>> signInPrizeList = shangJiMapper.listSignInPrize(reqMap);
        // 拿到用户已经填写的联系人和联系电话
        if (signInPrizeList.size() > 0) {
            responseData.put("contact_phoneNum", signInPrizeList.get(0).get("contact_phoneNum"));
            responseData.put("contact_name", signInPrizeList.get(0).get("contact_name"));
            responseData.put("address", signInPrizeList.get(0).get("address"));
        }
        responseData.put("status", true);
        responseData.put("draws_count", drawsCount);
        return responseData;
    }

    @Override
    public Map<String, Object> saveActivitySignInPrize(Map<String, Object> reqMap) throws MyException {
        Map<String, Object> responseData = new HashMap<>(3);
        // 保存对应的奖品记录
        reqMap.put("id", UuidUtil.get32UUID());
        // 抽奖奖品
        reqMap.put("type", 1);
        reqMap.put("is_receive", 0);
        shangJiMapper.insertSignInPrize(reqMap);
        responseData.put("status", true);
        return responseData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> saveActivitySignInPrizeNew(Map<String, Object> reqMap) throws MyException {
        String id = UuidUtil.get32UUID();
        // 保存对应的奖品记录
        reqMap.put("id", id);
        // 抽奖奖品
        reqMap.put("type", 1);
        reqMap.put("is_receive", 0);
        shangJiMapper.insertSignInPrize(reqMap);
        // 减少抽奖次数
        Map<String, Object> resultMap = this.activitySignInPrize(reqMap);
        resultMap.put("id", id);
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> listPrize(Map<String, Object> reqMap) {
        return personalCenterMapper.listPrize(reqMap);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> getShareInvitationCode(String userId) throws MyException {
        Map<String, Object> shareMap = this.getShareByUserId(userId),
                responseMap = new HashMap<>(3);
        if (shareMap != null) {
            responseMap.put("invitation_code", shareMap.get("invitation_code"));
            responseMap.put("share_person_num", shangJiMapper.countSharePerson(userId, 1));
            responseMap.put("status", true);
            return responseMap;
        } else {
            // 生成6位邀请码
            String invitationCode = ShareCodeUtil.generateShortUuid();
            Map<String, Object> reqMap = new HashMap<>(5);
            reqMap.put("id", UuidUtil.get32UUID());
            reqMap.put("user_id", userId);
            reqMap.put("invitation_code", invitationCode);
            // 保存邀请码信息
            shangJiMapper.insertShare(reqMap);
            // 返回数据
            responseMap.put("invitation_code", invitationCode);
            responseMap.put("share_person_num", 0);
            responseMap.put("status", true);
            return responseMap;
        }
    }

    @Override
    public List<Map<String, Object>> listSharePrizeSelf(String userId) throws MyException {
        Map<String, Object> reqMap = new HashMap<>();
        // 抽奖奖品
        reqMap.put("type", 2);
        reqMap.put("user_id", userId);
        return shangJiMapper.listSignInPrize(reqMap);
    }

    @Override
    public List<Map<String, Object>> listMyInvitePeople(User currentUser) throws MyException {
        return shangJiMapper.listMyInvitePeople(currentUser.getId());
    }

    @Override
    public Map<String, Object> savePrizeRecipient(Map<String, Object> reqMap) throws MyException {
        if (reqMap.get("contact_name") == null && StringUtils.isBlank(reqMap.get("contact_name").toString())
                && reqMap.get("contact_phoneNum") == null && StringUtils.isBlank(reqMap.get("contact_phoneNum").toString())) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "参数不正确");
        }
        Map<String, Object> resultMap = new HashMap<>(2);
        shangJiMapper.updatePrizeRecipient(reqMap);
        return resultMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Map<String, Object>> listSharePrizeLastTenData() throws MyException {
        List<Map<String, Object>> sharePrizeList = shangJiMapper.listSharePrizeLastTenData();
        for (Map<String, Object> sharePrize : sharePrizeList) {
            // 获取已经成功分享次数
            Map<String, Object> shareRcordQuery = new HashMap<>();
            shareRcordQuery.put("user_id", sharePrize.get("user_id").toString());
            // 已经成功分享次数
            int shareRcordNum = shangJiMapper.listShareRecord(shareRcordQuery).size();
            sharePrize.put("share_rcord_num", shareRcordNum);
        }
        // 不足10条数据，补充假数据
        if (sharePrizeList.size() < 10) {
            List<Map<String, Object>> dummyPrizeData = this.createSharePrizeData(10 - sharePrizeList.size());
            sharePrizeList.addAll(dummyPrizeData);
        }
        // 屏蔽联系人姓名，*号处理
        this.shieldContactName(sharePrizeList);
        return sharePrizeList;
    }

    /**
     * 获取最新10条分享得到的流量(虚拟数据)
     * @return
     */
    public List<Map<String, Object>> listShareAppLastTenData() {
        List<Map<String, Object>> dummyPrizeData = this.createShareAppData(10);
        this.shieldContactName(dummyPrizeData); // 屏蔽联系人姓名，*号处理

        return dummyPrizeData;
    }

    /**
     * 创建num条数的假数据
     *
     * @param num
     * @return
     */
    private List<Map<String, Object>> createSharePrizeData(int num) {
        List<Map<String, Object>> sharePrizeList = new ArrayList<>();
        Map<String, Object> sharePrize;
        for (int i = 0; i < num; i++) {
            int randomNum = new Random().nextInt(95) + 5;
            sharePrize = new HashMap<>();
            sharePrize.put("prize_name", this.randomPrizeName(randomNum));
            sharePrize.put("contact_name", this.randomName());
            sharePrize.put("share_rcord_num", randomShareRcordNum(randomNum));
            sharePrizeList.add(sharePrize);
        }
        return sharePrizeList;
    }

    /**
     * 创建num条数的假数据
     *
     * @param num
     * @return
     */
    private List<Map<String, Object>> createShareAppData(int num) {
        List<Map<String, Object>> sharePrizeList = new ArrayList<>();
        Map<String, Object> sharePrize;

        Random r = new Random();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(new Date());
        for (int i = 0; i < num - 3; i++) {
            sharePrize = new HashMap<>();
            sharePrize.put("contact_name", this.randomName());
            sharePrize.put("prize_name", Constants.dischargePattern[r.nextInt(2)]);
            sharePrize.put("mobile", Constants.mobileFirstPattern[r.nextInt(38)] + "****" + Math.round((Math.random() + 1) * 1000));
            sharePrize.put("fetch_date", dateStr);
            sharePrizeList.add(sharePrize);
        }

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1); // 当前时间减去一天，即一天前的时间
        String dateStrYesterday = sdf.format(calendar.getTime());
        for (int i = 0; i < 3; i++) {
            sharePrize = new HashMap<>();
            sharePrize.put("contact_name", this.randomName());
            sharePrize.put("prize_name", Constants.dischargePattern[r.nextInt(2)]);
            sharePrize.put("mobile", Constants.mobileFirstPattern[r.nextInt(38)] + "****" + Math.round((Math.random() + 1) * 1000));
            sharePrize.put("fetch_date", dateStrYesterday);
            sharePrizeList.add(sharePrize);
        }

        return sharePrizeList;
    }

    private String randomPrizeName(int randomNum) {
        if (randomNum >= 10 && randomNum < 28) {
            return Constants.SharePrizeNnum.getPrizeNameByNum(10);
        } else if (randomNum >= 28 && randomNum < 38) {
            return Constants.SharePrizeNnum.getPrizeNameByNum(28);
        } else if (randomNum >= 38 && randomNum < 50) {
            return Constants.SharePrizeNnum.getPrizeNameByNum(38);
        } else if (randomNum >= 50 && randomNum < 100) {
            return Constants.SharePrizeNnum.getPrizeNameByNum(50);
        } else if (randomNum == 100) {
            return Constants.SharePrizeNnum.getPrizeNameByNum(100);
        } else {
            return Constants.SharePrizeNnum.getPrizeNameByNum(5);
        }
    }

    private Integer randomShareRcordNum(int randomNum) {
        if (randomNum >= 10 && randomNum < 28) {
            return new Random().nextInt(17) + 10;
        } else if (randomNum >= 28 && randomNum < 38) {
            return new Random().nextInt(9) + 28;
        } else if (randomNum >= 38 && randomNum < 50) {
            return new Random().nextInt(11) + 38;
        } else if (randomNum >= 50 && randomNum < 100) {
            return new Random().nextInt(49) + 50;
        } else if (randomNum == 100) {
            return 100;
        } else {
            return new Random().nextInt(4) + 5;
        }
    }

    private String randomName() {
        int randomNum = new Random().nextInt(100);
        if (randomNum >= 0 && randomNum < 5) {
            return "赵--";
        }
        if (randomNum >= 5 && randomNum < 10) {
            return "钱--";
        }
        if (randomNum >= 10 && randomNum < 15) {
            return "孙--";
        }
        if (randomNum >= 15 && randomNum < 20) {
            return "李--";
        }
        if (randomNum >= 20 && randomNum < 25) {
            return "周--";
        }
        if (randomNum >= 25 && randomNum < 30) {
            return "周--";
        }
        if (randomNum >= 35 && randomNum < 40) {
            return "吴--";
        }
        if (randomNum >= 45 && randomNum < 50) {
            return "郑--";
        }
        if (randomNum >= 55 && randomNum < 60) {
            return "王--";
        }
        if (randomNum >= 65 && randomNum < 70) {
            return "冯--";
        }
        if (randomNum >= 75 && randomNum < 80) {
            return "陈--";
        }
        if (randomNum >= 85 && randomNum < 90) {
            return "褚--";
        }
        return "卫--";
    }

    private List<Map<String, Object>> shieldContactName(List<Map<String, Object>> sharePrizeList) {
        for (Map<String, Object> sharePrize : sharePrizeList) {
            String contcatName = sharePrize.get("contact_name").toString();
            sharePrize.put("contact_name", contcatName.replaceAll("(?<=.).", "*"));
        }
        return sharePrizeList;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> useShareInvitationCode(User user, Map<String, Object> reqMap) throws MyException {
        Map<String, Object> responseMap = new HashMap<>(2);
        String userId = reqMap.get("user_id").toString();
        String invitationCode = reqMap.get("invitation_code").toString();
        if (StringUtils.isBlank(invitationCode)) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "请填写分享码");
        }
        // 查询分享表数据，获取分享推荐码对应的分享人userId
        Map<String, Object> shareMap = this.getShareByInvitationCode(invitationCode);
        if (shareMap == null) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "分享码不存在");
        }
        String shareUserId = shareMap.get("user_id").toString();
        // 如果分享人的userid和被分享人的userid想同，则是分享给自己，不处理
        if (userId.equals(shareUserId)) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "不能分享给自己");
        }
        // 查询被分享成功列表
        Map<String, Object> shareRcordedQuery = new HashMap<>();
        shareRcordedQuery.put("other_user_id", userId);
        List<Map<String, Object>> shareRcordedList = shangJiMapper.listShareRecord(shareRcordedQuery);
        // 如果当前用户已经被别的用户邀请成功了，则不处理
        if (shareRcordedList.size() > 0) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "您已经被邀请了，不能再进行此操作");
        }
        Map<String, Object> shareRecordMap = new HashMap<>(3);
        shareRecordMap.put("id", UuidUtil.get32UUID());
        shareRecordMap.put("user_id", shareUserId);
        shareRecordMap.put("other_user_id", userId);
        // 保存分享记录
        shangJiMapper.insertShareRecord(shareRecordMap);
        responseMap.put("status", true);
        // 获取已经成功分享次数
        Map<String, Object> shareRcordQuery = new HashMap<>();
        shareRcordQuery.put("user_id", shareUserId);
        List<Map<String, Object>> shareRcordList = shangJiMapper.listShareRecord(shareRcordQuery);
        // 已经成功分享次数
        int shareRcordNum = shareRcordList.size();
        // 保存奖品
        saveSharePrize(shareRcordNum, userService.getUserById(shareUserId));
        return responseMap;
    }

    /**
     * 分享保存奖品
     *
     * @param shareRcordNum
     * @param userMap
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveSharePrize(int shareRcordNum, Map<String, Object> userMap) {
        // 获取奖品
        String prizeName = Constants.SharePrizeNnum.getPrizeNameByNum(shareRcordNum);
        if (prizeName == null) {
            return false;
        }
        // 保存奖品信息
        Map<String, Object> prizeMap = new HashMap<>();
        prizeMap.put("id", UuidUtil.get32UUID());
        prizeMap.put("user_id", userMap.get("id"));
        prizeMap.put("prize_name", prizeName);
        prizeMap.put("contact_name", userMap.get("user_name"));
        prizeMap.put("contact_phoneNum", userMap.get("user_account"));
        prizeMap.put("type", 2);
        shangJiMapper.insertSignInPrize(prizeMap);
        return true;
    }


    @Override
    public Map<String, Object> getShareByUserId(String userId) throws MyException {
        Map<String, Object> reqMap = new HashMap<>(3);
        reqMap.put("user_id", userId);
        return shangJiMapper.selectShare(reqMap);
    }

    @Override
    public Map<String, Object> getShareByInvitationCode(String invitationCode) throws MyException {
        Map<String, Object> reqMap = new HashMap<>(3);
        reqMap.put("invitation_code", invitationCode);
        return shangJiMapper.selectShare(reqMap);
    }

    @Override
    public void updateBrowseRandom() {
        int timeFlag;
        LocalDate currentDate = LocalDate.now();
        List<Map<String, Object>> noUpdatedBrowseWithShopInfoList = shangJiMapper.listNoUpdatedBrowseWithShopInfo();
        for (Map<String, Object> noUpdatedBrowseWithShopInfo : noUpdatedBrowseWithShopInfoList) {
            timeFlag = this.wrapHandleFlag(noUpdatedBrowseWithShopInfo, currentDate);
            if (timeFlag == -1) {
                continue;
            }
            String id = noUpdatedBrowseWithShopInfo.get("id").toString();
            shangJiMapper.updateOrdersRandomWithShopInfo(id, timeFlag);
            shangJiMapper.updateBrowseRandomWithShopInfo(id, timeFlag);
            shangJiMapper.updateTelConsultRandomWithShopInfo(id);
        }
        List<Map<String, Object>> noUpdatedBrowseWithJoberInfoList = shangJiMapper.listNoUpdatedBrowseWithJoberInfo();
        for (Map<String, Object> noUpdatedBrowseWithJoberInfo : noUpdatedBrowseWithJoberInfoList) {
            timeFlag = this.wrapHandleFlag(noUpdatedBrowseWithJoberInfo, currentDate);
            if (timeFlag == -1) {
                continue;
            }
            String id = noUpdatedBrowseWithJoberInfo.get("id").toString();
            shangJiMapper.updateBrowseRandomWithJoberInfo(id, timeFlag);
            shangJiMapper.updateTelConsultRandomWithJoberInfo(id);
        }
        List<Map<String, Object>> noUpdatedBrowseWithRecruitInfoList = shangJiMapper.listNoUpdatedBrowseWithRecruitInfo();
        for (Map<String, Object> noUpdatedBrowseWithRecruitInfo : noUpdatedBrowseWithRecruitInfoList) {
            timeFlag = this.wrapHandleFlag(noUpdatedBrowseWithRecruitInfo, currentDate);
            if (timeFlag == -1) {
                continue;
            }
            String id = noUpdatedBrowseWithRecruitInfo.get("id").toString();
            shangJiMapper.updateBrowseRandomWithRecruitInfo(id, timeFlag);
            shangJiMapper.updateTelConsultRandomWithRecruitInfo(id);
        }
        List<Map<String, Object>> noUpdatedBrowseWithBuyInfoList = shangJiMapper.listNoUpdatedBrowseWithBuyInfo();
        for (Map<String, Object> noUpdatedBrowseWithBuyInfo : noUpdatedBrowseWithBuyInfoList) {
            timeFlag = this.wrapHandleFlag(noUpdatedBrowseWithBuyInfo, currentDate);
            if (timeFlag == -1) {
                continue;
            }
            String id = noUpdatedBrowseWithBuyInfo.get("id").toString();
            shangJiMapper.updateBrowseRandomWithBuyInfo(id, timeFlag);
            shangJiMapper.updateTelConsultRandomWithBuyInfo(id);
        }
    }

    private int wrapHandleFlag(Map<String, Object> noUpdatedBrowseWithShopInfo, LocalDate currentDate) {
        int timeFlag;
        LocalDate createTime = LocalDate.parse(noUpdatedBrowseWithShopInfo.get("create_time").toString().substring(0, 10));
        if (noUpdatedBrowseWithShopInfo.get("create_user") == null || StringUtils.isBlank(noUpdatedBrowseWithShopInfo.get("create_user").toString())) {
            timeFlag = 3;
        } else if (currentDate.minusDays(1L).equals(createTime)) {
            timeFlag = 1;
        } else if (createTime.isBefore(currentDate.minusDays(1))) {
            timeFlag = 2;
        } else {
            timeFlag = -1;
        }
        return timeFlag;
    }

    @Override
    public Map<String, Object> getBannerPicPathList(User user) throws IOException {
        Map<String, Object> resMap = new HashMap<>();
        if (StringUtils.isBlank(user.getS_id())) {
            resMap.put("flag", false);
            resMap.put("picPaths", Collections.emptyList());
            return resMap;
        }
        List<String> picPaths = new ArrayList<>();
        String bannerPicPathTmp = "upload/avatar/servers/%s";
        String bannerPicPath = String.format(bannerPicPathTmp, user.getS_id());
        List<ObsObject> result = ObsUtils.selectObsObjects(bannerPicPath+"/");
        if (result.size() <= 0 ) {
            resMap.put("flag", false);
        } else {
            result.forEach(item ->{
                picPaths.add(item.getObjectKey());
            });
        }
//        String realPath = "D:\\nginx-1.15.5/html/web-mechanic/";
//        String bannerPicPathTmp = "upload/avatar/servers/%s";
//        String bannerPicPath = String.format(bannerPicPathTmp, user.getS_id());
//        String fullPath = realPath + bannerPicPath;
//        File file = new File(fullPath);
//        if (!file.exists()) {
//            resMap.put("flag", false);
//        } else {
//            File[] cFiles = file.listFiles();
//            if (cFiles != null) {
//                for (File cFile : cFiles) {
//                    picPaths.add(bannerPicPath + "/" + cFile.getName());
//                }
//            }
//        }
        resMap.put("picPaths", picPaths);
        return resMap;
    }

    @Override
    public int updateTelConsult(Map<String, Object> reqMap) throws MyException {
        int result = 0;
        if (reqMap.get("type") != null) {
            if ("维修服务".equals(reqMap.get("type").toString())) {
                reqMap.put("table_name", "publish_shop_info");
            } else if ("出租".equals(reqMap.get("type").toString()) || "出售".equals(reqMap.get("type").toString()) ||
                    "求租".equals(reqMap.get("type").toString()) || "求购".equals(reqMap.get("type").toString())) {
                reqMap.put("table_name", "zowe_buyinfo_detail");
            } else if ("企业招聘".equals(reqMap.get("type").toString())) {
                reqMap.put("table_name", "publish_recruit_info");
            } else if ("个人求职".equals(reqMap.get("type").toString())) {
                reqMap.put("table_name", "publish_jober_info");
            }
            if (reqMap.get("table_name") != null) {
                result = shangJiMapper.updateTelConsult(reqMap);
            }
        }
        return result;
    }

    /**
     * 修改招聘信息
     *
     * @param reqMap
     * @param currentUser
     * @return
     */
    @Override
    public int updateRecruitInfo(Map<String, Object> reqMap, User currentUser) {
        reqMap.put("user_id", currentUser.getId());
        List<String> treatments = (List<String>) reqMap.get("treatment");
        reqMap.put("treatment", String.join(",", treatments));
        int result = shangJiMapper.updateRecruitInfo(reqMap);
        return result;
    }

    /**
     * 修改求职信息
     *
     * @param reqMap
     * @param currentUser
     * @return
     */
    @Override
    public int updateJoberInfo(Map<String, Object> reqMap, User currentUser) {
        reqMap.put("user_id", currentUser.getId());
        int result = shangJiMapper.updateJoberInfo(reqMap);
        return result;
    }

    /**
     * 修改店铺信息
     *
     * @param reqMap
     * @param currentUser
     * @return
     */
    @Override
    public int updateShop(Map<String, Object> reqMap, User currentUser) {
        reqMap.put("user_id", currentUser.getId());
        reqMap.put("type_name", String.join(",", (List<String>) reqMap.get("type_name")));
        int result = shangJiMapper.updateShop(reqMap);
        return result;
    }

    /**
     * 修改租售信息
     *
     * @param reqMap
     * @param currentUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePublicCarDetail(Map<String, Object> reqMap, User currentUser) {
        reqMap.put("user_id", currentUser.getId());

        reqMap.put("examine_flag", 0); // 审核标志 0:未审核  1:审核通过 2:审核不通过；暂时审核状态设置为 1
        // isFromOPS表示从后市场创建的求购信息，暂不需要再次审核
        if ("求购".equals(reqMap.get("type").toString()) && reqMap.get("isFromOPS") != null) {
            reqMap.put("examine_flag", 1);
        }

        int result = shangJiMapper.updatePublicCarDetail(reqMap);
        if ("出售".equals(reqMap.get("type"))) {
            Map<String, Object> params = new HashMap<>();
            params.put("buyinfo_id", reqMap.get("id"));
            params.put("update_user", reqMap.get("user_id"));
            params.put("model_id", reqMap.get("model_id"));
            params.put("parent_model_id", reqMap.get("parent_model_id"));
            params.put("parent_brand_id", reqMap.get("parent_brand_id"));
            params.put("brand_id", reqMap.get("brand_id"));
            params.put("delete_flag", reqMap.get("delete_flag"));
            Map<String, Object> brandAndModel = shangJiMapper.getBrandAndModelByBuyInfoId(params.get("buyinfo_id").toString());
            if (brandAndModel != null) {
                shangJiMapper.updateBrandAndModelByBuyinfoId(params);
            } else {
                params.put("id", UuidUtil.get32UUID());
                shangJiMapper.addBrandAndModel(params);
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> getBannerPic(User user) {
        Map<String, Object> resultMap = new HashMap<>();

        List<Map<String, Object>> bannerList;
        List<Map<String, Object>> indexPicture;
        List<Map<String, Object>> personCenterPicture;

        if (isGuest(user)) {
            bannerList = shangJiMapper.getBannerListNew("0", 0);
            indexPicture = shangJiMapper.getBannerListNew("0", 1);
            personCenterPicture = shangJiMapper.getBannerListNew("0", 2);
        } else {
            String sId = user.getS_id();
            int bannerCount = shangJiMapper.isSetBanner(sId, 0);
            int indexPictureCount = shangJiMapper.isSetBanner(sId, 1);
            int personCenterPictureCount = shangJiMapper.isSetBanner(sId, 2);
            if (bannerCount > 0) {
                bannerList = shangJiMapper.getBannerListNew(sId, 0);
            } else {
                bannerList = shangJiMapper.getBannerListNew("0", 0);
            }
            if (indexPictureCount > 0) {
                indexPicture = shangJiMapper.getBannerListNew(sId, 1);
            } else {
                indexPicture = shangJiMapper.getBannerListNew("0", 1);
            }
            if (personCenterPictureCount > 0) {
                personCenterPicture = shangJiMapper.getBannerListNew(sId, 2);
            } else {
                personCenterPicture = shangJiMapper.getBannerListNew("0", 2);
            }
        }
        resultMap.put("bannerList", bannerList);
        resultMap.put("indexPicture", indexPicture);
        resultMap.put("personCenterPicture", personCenterPicture);
        return resultMap;
    }

    //该方法未被使用，暂不修改
    @Override
    public List<Map<String, Object>> copyBuyInfoFile(Map<String, Object> map) {
        String rootPath = "D:/nginx-1.15.5/html/web-mechanic/";
        String rootTargetPath = rootPath + "upload/chushou/";
        List<Map<String, Object>> buyInfos = shangJiMapper.getBuyInfoFile();

        String isExecuteSql = "2";
        if (map.get("isExecuteSql") != null) {
            isExecuteSql = map.get("isExecuteSql").toString();
        }

        for (Map<String, Object> buyInfo : buyInfos) {
            String image = buyInfo.get("image").toString();
            String createUser = buyInfo.get("create_user").toString();
            String id = buyInfo.get("id").toString();
            if (image.split("/").length == 5) {
                try {
                    String newImage = this.pictureHandle(buyInfo, "image", rootPath, rootTargetPath, createUser);
                    String newThumFileName = this.pictureHandle(buyInfo, "thumFileName", rootPath, rootTargetPath, createUser);
                    String newDetailPicture = this.pictureHandle(buyInfo, "detail_picture", rootPath, rootTargetPath, createUser);
                    String imageFirst = this.pictureHandle(buyInfo, "imagefirst", rootPath, rootTargetPath, createUser);

                    if ("1".equals(isExecuteSql)) {
                        shangJiMapper.updateBuyInfoFilePath(newImage, newThumFileName, newDetailPicture, imageFirst, id);
                    }
                } catch (IOException e) {
                    logger.error("出售图片拷贝失败：id:" + id);
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private String pictureHandle(Map<String, Object> buyInfo, String key, String rootPath, String rootTargetPath, String createUser) throws IOException {
        if (buyInfo.get(key) != null && StringUtils.isNotBlank(buyInfo.get(key).toString())) {
            String picture = buyInfo.get(key).toString();
            String[] pictures = picture.split(",");
            String returnPicture = this.copyFileAndReturnNewPaths(pictures, rootPath, rootTargetPath, createUser);
            return returnPicture.substring(returnPicture.indexOf("upload"));
        }
        return null;
    }

    private String copyFileAndReturnNewPaths(String[] pictures, String rootPath, String rootTargetPath, String createUser) throws IOException {
        LinkedList<String> newPaths = new LinkedList<>();
        for (String picture : pictures) {
            String[] picturePaths = picture.split("/");
            String originPath = rootPath + picture;
            String targetPath = rootTargetPath + createUser + "/" + picturePaths[3] + "/" + picturePaths[4];
            FileUtils.copyFile(new File(originPath), new File(targetPath));
            newPaths.addLast(targetPath);
        }
        return String.join("/", newPaths);
    }

    /**
     * 添加用户行为分数
     *
     * @param reqMap
     */
    public int insertUserBehavior(Map<String, Object> reqMap, int behaviorType, int behav, User currentUser, String device) {
        int result = 0;
        reqMap.put("behavior_type", behaviorType);
        reqMap.put("behavior", behav);
        reqMap.put("id", UuidUtil.get32UUID());
        //获取行为类型和该行为的分数
        int behavior = Integer.parseInt(reqMap.get("behavior").toString());
        int score = Constants.UserBehaviorEnum.getScoreByBehavior(behavior);
        reqMap.put("behavior_score", score);
        if (currentUser != null) {
            reqMap.put("user_id", currentUser.getId());
        }
        if (!"".equals(device)) {
            reqMap.put("device", device);
        } else {
            //暂时没有传设备号
            //用户登录了
            if(currentUser != null){
                //判断用户是否有该类型的行为
                int isNoDeviceLogin = shangJiMapper.isLoginDevice(reqMap);
                //如果有 就加上这次行为的分数
                if(isNoDeviceLogin > 0){
                    Integer currentScore = shangJiMapper.getCurrentScore(reqMap);
                    if (currentScore == null) {
                        currentScore = 0;
                    }
                    score += currentScore;
                    reqMap.put("behavior_score", score);
                    result = shangJiMapper.updateUserBehavior(reqMap);
                }else{
                    //否则直接新增
                    result = shangJiMapper.insertUserBehavior(reqMap);
                }
            }
            return result;
        }
        //处于登录状态
        if (reqMap.get("user_id") != null) {
            //查询是否有该用户登录的但没有设备号的此类型的行为
            reqMap.put("device",null);
            int noDevice = shangJiMapper.isLoginDevice(reqMap);
            if(noDevice > 0){
                reqMap.put("device",device);
                //查询是否有绑定了此设备 但是没有绑定user_id的数据
                int isBindDeviceNoUser = shangJiMapper.getIsBindDeviceNoUser(reqMap);
                if(isBindDeviceNoUser > 0){
                    //如果有 获取所有的绑定了该设备但是没有绑定user_id的数据
                    List<Map<String,Object>> dataList = shangJiMapper.getDataBindDeviceNoUser(reqMap);
                    for(Map<String,Object> map:dataList){
                        int type = (int)map.get("behavior_type");
                        reqMap.put("behavior_type",type);
                        reqMap.put("device",null);
                        Integer currentScore = shangJiMapper.getCurrentScore(reqMap);
                        if (currentScore == null) {
                            currentScore = 0;
                        }
                        reqMap.put("device",device);
                        int beforeScore = (int)map.get("behavior_score");
                        if(type == behaviorType){
                            score = Constants.UserBehaviorEnum.getScoreByBehavior(behavior);
                            beforeScore += score;
                        }
                        score = currentScore + beforeScore;
                        reqMap.put("behavior_score",score);
                        shangJiMapper.updateDeviceScore(reqMap);
                    }
                }else{
                    //如果没有 将之前用户没有设备号的该类型数据绑定到此设备上,并加分
                    reqMap.put("device",null);
                    Integer currentScore = shangJiMapper.getCurrentScore(reqMap);
                    if (currentScore == null) {
                        currentScore = 0;
                    }
                    score += currentScore;
                    reqMap.put("behavior_score", score);
                    reqMap.put("user_id", currentUser.getId());
                    reqMap.put("device",device);
                    result = shangJiMapper.updateNoDevice(reqMap);
                    //绑定之前该用户没有绑定设备的各种类型的行为
                    shangJiMapper.updateOthersNoDevice(reqMap);
                }
                return result;
            }

            reqMap.put("device",device);
            //根据用户id、设备号和类型 查询在用户设备表是否存在
            int isLoginDevice = shangJiMapper.isLoginDevice(reqMap);
            //存在：获取原来的分数加上当前行为的分数 修改表
            if (isLoginDevice > 0) {
                Integer currentScore = shangJiMapper.getCurrentScore(reqMap);
                if (currentScore == null) {
                    currentScore = 0;
                }
                score += currentScore;
                reqMap.put("behavior_score", score);
                result = shangJiMapper.updateUserBehavior(reqMap);
            } else {
                //不存在
                // 根据用户id、设备号和类型 查询在用户是否存在其他设备上登陆过并执行此类型操作
                int isLoginOthers = shangJiMapper.isLoginOthers(reqMap);
                //存在
                if (isLoginOthers > 0) {
                    //查询出此设备号 为最近登录的设备
                    String latestDevice = shangJiMapper.getLatestDevice(reqMap);
                    //根据此设备号查出最近一次登录设备的所有行为
                    List<Map<String, Object>> latestDeviceBehavior = shangJiMapper.getLatestDeviceBehavior(latestDevice, currentUser.getId());
                    for (Map<String, Object> behaviorMap : latestDeviceBehavior) {
                        //拷贝该设备里的数据 加上这次操作的分数 插入表
                        reqMap.put("id", UuidUtil.get32UUID());
                        reqMap.put("behavior_type", behaviorMap.get("behavior_type"));
                        reqMap.put("device", behaviorMap.get("device").toString());
                        Integer currentScore = shangJiMapper.getCurrentScore(reqMap);
                        if (currentScore == null) {
                            currentScore = 0;
                        }
                        if ((int) behaviorMap.get("behavior_type") == behaviorType) {
                            score = Constants.UserBehaviorEnum.getScoreByBehavior(behavior);
                            score += currentScore;
                        } else {
                            score = (int) behaviorMap.get("behavior_score");
                        }
                        reqMap.put("device", device);
                        reqMap.put("behavior_score", score);
                        result = shangJiMapper.insertUserBehavior(reqMap);
                    }
                } else {
                    //查询表里是否有该设备号和type并且userid为空的数据
                    int noUserDevice = shangJiMapper.getNoUserDevice(reqMap);
                    if (noUserDevice > 0) {
                        //如果存在,将userid绑定该设备并且加分
                        reqMap.put("user_id", null);
                        Integer currentScore = shangJiMapper.getCurrentScore(reqMap);
                        if (currentScore == null) {
                            currentScore = 0;
                        }
                        score += currentScore;
                        reqMap.put("behavior_score", score);
                        reqMap.put("user_id", currentUser.getId());
                        result = shangJiMapper.updateNoUserDevice(reqMap);
                        //并将该设备的其他type也绑定此userid
                        shangJiMapper.updateOthersDevice(reqMap);
                    } else {
                        //如果不存在,插入数据
                        result = shangJiMapper.insertUserBehavior(reqMap);
                    }
                }
            }
        } else {
            //没有用户登录 该设备在表里是否有该行为的记录
            int isDeviceExist = shangJiMapper.isLoginDevice(reqMap);
            //如果该设备在表里有该行为的记录 修改此条数据的分数
            if (isDeviceExist > 0) {
                Integer currentScore = shangJiMapper.getCurrentScore(reqMap);
                if (currentScore == null) {
                    currentScore = 0;
                }
                score += currentScore;
                reqMap.put("behavior_score", score);
                result = shangJiMapper.updateUserBehavior(reqMap);
            } else {
                //否则新增一条数据
                result = shangJiMapper.insertUserBehavior(reqMap);
            }
        }
        return result;
    }

    /**
     * 分享获取分数
     *
     * @param reqMap
     * @return
     */
    @Override
    public int shareBehavior(Map<String, Object> reqMap, User currentUser, String device) {
        int result = 0;
        int type = (int) reqMap.get("behavior_type");
        if (type == Constants.BEHAVIOR_BID_TYPE) {
            result = insertUserBehavior(reqMap, Constants.BEHAVIOR_BID_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_SHARE.getBehavior(), currentUser, device);
        } else if (type == Constants.BEHAVIOR_RECRUIT_TYPE) {
            result = insertUserBehavior(reqMap, Constants.BEHAVIOR_RECRUIT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_SHARE.getBehavior(), currentUser, device);
        } else if (type == Constants.BEHAVIOR_SALEANDRENT_TYPE) {
            result = insertUserBehavior(reqMap, Constants.BEHAVIOR_SALEANDRENT_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_SHARE.getBehavior(), currentUser, device);
        } else if (type == Constants.BEHAVIOR_SHOP_TYPE) {
            result = insertUserBehavior(reqMap, Constants.BEHAVIOR_SHOP_TYPE, Constants.UserBehaviorEnum.BEHAVIOR_SHARE.getBehavior(), currentUser, device);
        }
        return result;
    }

    @Override
    public Map<String, Object> getNewMachineList(Map<String, Object> reqMap,User user) {
        Map<String, Object> resultMap = new HashMap<>();
        this.appPage(reqMap);
        reqMap.put("isGuest", this.isGuest(user));
        if (!this.isGuest(user)) {
            reqMap.put("isCarMasterOrDriver", Constants.ROLE_SJ.equals(user.getR_id()) || Constants.ROLE_CZ.equals(user.getR_id()));
            reqMap.put("isServer", !(Constants.ROLE_SJ.equals(user.getR_id()) || Constants.ROLE_CZ.equals(user.getR_id())));
            reqMap.put("s_id", user.getS_id());
        }
        List<Map<String, Object>> modelList = shangJiDao.getNewMachineList(reqMap);

        for (Map<String, Object> buyInfo : modelList) {
            // 对价格字段值做特别处理
            buyInfo.put("price", this.priceHandle(buyInfo));
        }
        resultMap.put("modelList", modelList);

        return resultMap;
    }

    @Override
    public Map<String, Object> getNewMachineDetail(Map<String, Object> reqMap, User currentUser, String device) {

        Map<String, Object> buyInfo = shangJiDao.getNewMachineDetail(reqMap);
        buyInfo.put("price", this.priceHandle(buyInfo));
        shangJiDao.updateNewMachineBrowser(buyInfo);
        return buyInfo;
    }
}
